build.gradle写入依赖
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
kotlin
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
object Tools {
private val viewModelJob = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private val workScope = CoroutineScope(Dispatchers.IO + viewModelJob)
@JvmStatic
fun test(task:Runnable) {
var str = "abc"
workScope.launch {
log(" str = $str")
log(" workScope.launch ${Thread.currentThread().name}")
str = "cdefg"
uiScope.launch {
task.run()
log(" str = $str")
log(" uiScope.launch ${Thread.currentThread().name}")
}
}
}
fun log(msg:String){
Log.d("debug_tag",msg)
}
}
java调用:
public void test(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d("debug_tag","java runnable " + Thread.currentThread().getName());
}
};
Tools.test(runnable);
}
运行结果如下:
2022-02-21 17:00:07.467 20320-20381/com.jetpack.paging D/debug_tag: str = abc
2022-02-21 17:00:07.468 20320-20381/com.jetpack.paging D/debug_tag: workScope.launch DefaultDispatcher-worker-1
2022-02-21 17:00:07.470 20320-20320/com.jetpack.paging D/debug_tag: java runnable main
2022-02-21 17:00:07.471 20320-20320/com.jetpack.paging D/debug_tag: str = cdefg
2022-02-21 17:00:07.471 20320-20320/com.jetpack.paging D/debug_tag: uiScope.launch main
|