本例使用协程和线程两个方式执行一段任务:
协程:任务是每秒打印出两个*->,运行100_000个任务;
@Test
fun testMet() = runBlocking { // this: CoroutineScope
val start = System.currentTimeMillis()
println("start time $start")
coroutineScope {
repeat(100_000) {
//协程方式
launch {
print("*->$it")
delay(500L)
}
}
}
println()
val end = System.currentTimeMillis()
println("end time$end")
println("耗时:${end - start}")
}
测试耗时:1247ms
采用线程:
@Test
fun testMet01() = runBlocking { // this: CoroutineScope
val start = System.currentTimeMillis()
println("start time $start")
coroutineScope {
repeat(100_000) {
//线程方式
Thread {
print("*->$it")
Thread.sleep(500L)
}.start()
}
}
println()
val end = System.currentTimeMillis()
println("end time$end")
println("耗时:${end - start}")
}
测试耗时:15325ms