赞
踩
// An highlighted block fun main() { /** * println("start") //主线程 * val user = getUserInfo() //耗时 * println(user) //主线程 * val friendList = getFriendList(user)//耗时 * println(friendList)//主线程 * val feedList= getFeedList(friendList)//耗时 * println(feelList)//主线程 */ //主线程调用 Main.execute { loginWebsintFun(LoginWebsiteImpl()) } } //主线程 val Main = Executors.newSingleThreadExecutor { runnable -> Thread(runnable).also { it.name = "main" } } //IO线程 val Io = Executors.newSingleThreadExecutor { runnable -> Thread(runnable).also { it.name = "Io" } } //Callback interface Continuation<in T> { fun resumeWith(result: T) } class LoginWebsiteImpl : Continuation<String> { var label: Int = 0 var result: String? = null override fun resumeWith(_result: String) { result = _result return loginWebsintFun(this) } } fun loginWebsintFun(continuateion: LoginWebsiteImpl) { when (continuateion.label) { 0 -> { println("start thread:" + Thread.currentThread().name) continuateion.label = 1 if (getUserInfo(continuateion) == 1) { return } } 1 -> { println("result: ${continuateion.result} " + Thread.currentThread().name) continuateion.label = 2 if (getFriendList(continuateion.result!!, continuateion) == 1) { return } } 2 -> { println("result ${continuateion.result} " + Thread.currentThread().name) continuateion.label = 3 if (getFeedList(continuateion.result!!, continuateion) == 1) { return } } 3->{ println("result ${continuateion.result} " + Thread.currentThread().name) } } } //step1 fun getUserInfo(continuation: Continuation<String>): Any? { Io.execute { //开始执行耗时操作 println("getUseInfo.... thread:" + Thread.currentThread().name) Thread.sleep(1000) //操作完成,进行下一步 Main.execute { continuation.resumeWith("userName:Tom") } } return 1 } //step2 fun getFriendList(userName: String, continuation: Continuation<String>): Any? { Io.execute { //开始执行耗时操作 println("getFriendList by ${userName}..... thread:" + Thread.currentThread().name) Thread.sleep(1000) //操作完成,进行下一步 Main.execute { continuation.resumeWith("Li,Wang,Zhang") } } return 1 } //step3 fun getFeedList(friendList: String, continuation: Continuation<String>): Any { Io.execute { //开始执行耗时操作 println("getFeedList by ${friendList}..... thread:" + Thread.currentThread().name) Thread.sleep(1000) //操作完成,进行下一步 Main.execute { continuation.resumeWith("feed1,feed2,feed3") } } return 1 }
运行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。