Kotlin Coroutines的详细指南(附代码)

359 阅读3分钟

Kotlin Coroutines

Kotlin Coroutines简介

kotlin Coroutines是一种功能,可用于将包括数据库、网络访问在内的长期运行任务的异步回调转换为顺序代码;长期运行任务是指需要太长时间来阻塞主线程的主要任务,而且主要的安全性是允许确保从主线程调用任何暂停功能,因此coroutine本身的代码块可以作为参数传递给实时数据构建器,也可以作为观察时运行coroutine的每个对象。

语法

在kotlin语言中,有许多默认的包,因此我们包括一些高级包和功能,如coroutine。因此,我们使用Kotlinx jars导入了coroutine,在此基础上对代码中的类和方法进行了调用。

import kotlinx.coroutines.*
fun main() = runBlocking { // It’s the CoroutineScope
launch{ // default method for creating coroutine and continue the task
delay(values) // default methods for blocking and non-blocking delays
}

上面的代码是在kotlin代码中创建和分配coroutine的基本语法。我们使用了默认的方法来利用coroutine类型的任务。

Coroutine在Kotlin中是如何工作的?

  • Coroutine是实例的一种类型,它是可暂停计算的概念,类似于线程,在这个意义上,它需要一个连续运行的代码块,与代码的其他部分一起工作。像coroutine一样,特定的线程可以暂停其在一级线程中的执行流程,并在另一个线程中恢复。
  • 一般来说,coroutines可以被认为是轻量级的线程,但是有一些重要的区别使得它们在现实生活中的使用与线程不同。我们使用了默认的方法,比如launch(),而delay()是coroutine生成器,用于创建coroutine,并同时执行代码的其余部分,这些代码继续独立工作。
  • delay()是一个暂停函数;它可以在一个特定的时间内暂停该循环程序。暂停该程序并不阻塞底层线程,但允许其他程序运行并使用底层线程来编写代码。类似地,runBlocking是coroutine构建器,它使用开括号和闭括号来连接常规范围的非coroutine世界。当我们在应用程序中使用线程时,它在调用的过程中具有创建、执行和阻塞功能,直到所有的coroutine都在开括号和闭括号内。

Kotlin Coroutines的例子

下面给出了Kotlin Coroutines的例子。

例子#1

代码

import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.*
suspend fun demo(){
println("The Suspended function used for to access and un-access the datas which is alreday decalred by the user end")
val a = listOf('A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
println(a.size)
println(a.indexOf(23))
println(a[14])
for(j in a.indices){
println(a[j])
}
}
suspend fun firstExample() = coroutineScope {
launch {
delay(23L)
val x = listOf("January is the first month", "February is the second month", "March is the third month", "April is the fourth month", "May is the fifth month", "June is the sixth month", "July is the seventh month", "August is the eigth month", "September is the nineth month", "October is the tenth month", "November is the eleventh month", "December is the twelth month")
println("The month details are: $x")
for(j in x.indices){
println(x[j])
}
val b = listOf("Tv is first electrical appliance","Fridge is the second appliance","Washing machine is third appliance", "Fridge is fourth appliance", "Laptop is fifth appliance", "PC is sixth appliance", "Microwave oven is seventh appliance", "Ups-Inverter is eigth appliance", "Mobile is electronic device","Fan is tenth appliance")
val res = b.get(6)
println(res)
val res1 = b[3]
println(res1)
val out1 = b.indexOf("Laptop")
println("The first index of number is $out1")
val out2 = b.lastIndex
println("The last index of the list is $out2")
}
println("Tke kotlin coroutine packages are successfully created and utilised in the application")
}
fun main(args: Array<String>) = runBlocking{
println("Welcome To My Domain its the first example that related to the kotlin coroutine")
launch(CommonPool) {
delay(32)
demo()
println("Have a Nice day users please try again")
}
println("The values are entered using the coroutine packages")
firstExample()
}

输出

Kotlin Coroutines 1

在上面的例子中,我们使用了具有集合功能的轮回类。

例子 #2

代码

import kotlinx.coroutines.*
fun secondExample(str: String) = println("[${Thread.currentThread().name}] $str")
fun main() = runBlocking<Unit> {
launch {
println("Its the main runBlocking thread ${Thread.currentThread().name}")
val a = launch {
delay(23L)
println("First Launch!")
}
a.join()
repeat(23) {
launch {
delay(12L)
}
}
}
launch(Dispatchers.Unconfined) {
println("The second launch thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) {
println("The third launch thread ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("string")) {
println("The fourth launch thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
println("The fifth launch thread ${Thread.currentThread().name}")
delay(24)
println("The fifth launch after delaying thread ${Thread.currentThread().name}")
}
launch {
println("The sixth launch thread ${Thread.currentThread().name}")
delay(34)
println("The sixth launch after delaying thread ${Thread.currentThread().name}")
}
val x = async {
secondExample("String value1")
4
}
val y = async {
secondExample("String value2")
3
}
secondExample("The state is awaiting section ${x.await() * y.await()}")
}

输出:

Kotlin Coroutines 2

在第二个例子中,我们创建了带有一些异步线程执行的 launch{} 块。

例子 #3

代码:

import kotlinx.coroutines.*
import java.text.SimpleDateFormat
import java.util.*
fun main() = runBlocking {
println("The third example related to the kotlin coroutine")
GlobalScope.launch {
println("The global scope is started")
delay(24L)
println("The scope task is finished")
}
println("STill it continues the main program task")
runBlocking {
delay(20L)
println("main program task is finished")
}
val a = async { example1() }
val b = async { example2() }
duration("The example 1 is executed waiting")
val out = a.await() + b.await()
duration("The out is $out")
}
suspend fun example1(): Int {
delay(12L)
duration("example1 is completed")
return 54
}
suspend fun example2(): Int {
delay(34L)
duration("example2 is completed")
return 6
}
fun duration(str: String) {
val z = (SimpleDateFormat("mm:hh:ss")).format(Date())
println("[$z] $str")
}

输出

we used time duration

在最后一个例子中,我们使用了时间长度与轮回线程。

总结

在kotlin语言中,用异步和非阻塞的代码实现了一个循环线程。基本上,它是使用语言中的暂停函数来实现的,冠状线的作用域和构建器被用来定义冠状线。异常被视为未捕获的异常,并被处理为打印到控制台。