Skip to content

Instantly share code, notes, and snippets.

@fathonyfath
Last active September 10, 2020 08:51
Show Gist options
  • Save fathonyfath/aba03308d56fac1cff20ce9c63fb1337 to your computer and use it in GitHub Desktop.
Save fathonyfath/aba03308d56fac1cff20ce9c63fb1337 to your computer and use it in GitHub Desktop.
Simple example difference between multithreaded vs non-multithreaded code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:format24Hour="HH:mm:ss"
android:format12Hour="hh:mm:ss a"
android:layout_gravity="center_horizontal"
android:layout_marginTop="24dp" />
<Button
android:id="@+id/nonMultiThreadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="24dp"
android:text="Heavy Task Non Multithread" />
<Button
android:id="@+id/multiThreadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Heavy Task Multithread" />
<Button
android:id="@+id/coroutineButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Heavy Task Coroutine" />
</LinearLayout>
package id.thony.examplethread
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nonMultiThreadButton.setOnClickListener { heavyTaskNonMultiThread() }
multiThreadButton.setOnClickListener { heavyTaskMultiThread() }
coroutineButton.setOnClickListener {
GlobalScope.launch {
heavyTaskCoroutine()
}
}
}
private fun heavyTaskNonMultiThread() {
Thread.sleep(5000)
Toast.makeText(this, "Heavy task complete!", Toast.LENGTH_SHORT).show()
}
private fun heavyTaskMultiThread() {
Thread {
Thread.sleep(5000)
this.runOnUiThread {
Toast.makeText(this, "Heavy task complete!", Toast.LENGTH_SHORT).show()
}
}.start()
}
private suspend fun heavyTaskCoroutine() {
delay(5000)
withContext(Dispatchers.Main) {
Toast.makeText(this@MainActivity, "Heavy task complete!", Toast.LENGTH_SHORT).show()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment