kotlin 使用篇 推荐 https://www.jianshu.com/u/a324daa6fa19
协程使用01
fun onclick1(view: View) {
//线程环境 切换协程环境
runBlocking {
//协程环境 Main 线程
launch {
//内协程
Log.e("click1","launch ${Thread.currentThread().name}")
}
// 工作线程
launch(Dispatchers.IO){
Log.e("click1","launch ${Thread.currentThread().name}")
repeat(10){
Thread.sleep(1000)
Log.e("click1","计数中:$it")
}
}
}
}
协程使用02
fun onclick2(view: View) = runBlocking{
launch {
//可以拿到异步执行后的结果
val def = async(Dispatchers.IO) {
true
"String"
}
// awaut --> main 线程
val result = def.await()
}
}
协程使用03
fun onclick3(view: View) {
//阻塞式的
runBlocking {
val dialog = ProgressDialog(this@MainActivity)
dialog.setMessage("Ing......")
dialog.show()
launch {
withContext(Dispatchers.IO){
Thread.sleep(1000)
Log.e("click3","耗时操作1")
}
withContext(Dispatchers.IO){
Thread.sleep(1000)
Log.e("click3","耗时操作2")
}
}
}
}
协程使用04
fun onclick4(view: View) {
//非阻塞式的
GlobalScope.launch(Dispatchers.Main) {
val dialog = ProgressDialog(this@MainActivity)
dialog.setMessage("Ing......")
dialog.show()
withContext(Dispatchers.IO){
Thread.sleep(1000)
Log.e("click3","耗时操作1")
}
withContext(Dispatchers.IO){
Thread.sleep(1000)
Log.e("click3","耗时操作2")
}
}
}
Demo01.kt
fun main(){
//非阻塞,类似与守护线程
GlobalScope.launch {
delay(1000)
println("11111111")
}
println("A")
Thread.sleep(200)
println("B")
}
Demo02.kt
fun main() {
//外协程
runBlocking {
//非阻塞,类似与守护线程
GlobalScope.launch {
delay(1000)
println("11111")
}
println("A")
//阻塞式执行的
//delay(2000)
delay(300)
println("B")
}
}
Demo03.kt
//suspend 挂起 函数 标记
suspend fun main() {
val job = GlobalScope.launch {
repeat(100){
delay(30)
println("report:$it")
}
}
println("A")
//我等你100毫秒
Thread.sleep(200)
//job.cancel()//有一点点的时间差
job.cancelAndJoin()// 没有时间差
}
网友评论