AM_*_*AM_ 3 multithreading android executor kotlin-coroutines
我在帖子中读到 Coroutine 不是在启动屏幕上使用的好习惯,而 Executors 是最好的,因为 Coroutine 比 Executors 需要更多时间来启动,但我没有找到实现它的例子,是 Executors是用于管理线程池的普通java Executor 类吗?
首先,飞溅的最佳性能,你必须阅读由威廉·里德的评论中提到的链接在这里,并在这里,也该链接等在这里
当您阅读文章时,请专注于这些词
在可调试的应用程序上进行的测量与生产性能惊人地不同
正如杰克沃顿指出的那样,差异部分是由于 ExecutorService 由 Zygote 预加载,Zygote 是 Android 框架的一个特殊部分,可在进程之间共享代码。其他并发框架,如协程,没有预加载,也会有相对较高的初始化成本。也就是说,协程比 ExecutorService 有很多优势。它们有作用域、挂起函数,它们比线程轻得多,等等。在 Android 应用程序中使用它们的一般建议是合理的,但它们令人印象深刻的功能集目前有一个初始化成本。或许 Kotlin 和 Android 团队将来可以优化这一点。在此之前,如果启动时间是主要问题,最好避免在 Application 类或主 Activity 中使用协程。
其次,对于您问题的另一部分,我认为那是您询问的Executor
在这里如何使用它
1 - 在主线程中执行代码
// Create an executor that executes tasks in the main thread.
val mainExecutor = ContextCompat.getMainExecutor(this)
// Execute a task in the main thread
mainExecutor.execute {
// You code logic goes here.
}
Run Code Online (Sandbox Code Playgroud)
2 - 在后台线程中执行代码
// Create an executor that executes tasks in a background thread.
val backgroundExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
// Execute a task in the background thread.
backgroundExecutor.execute {
// Your code logic goes here.
}
// Execute a task in the background thread after 3 seconds.
backgroundExecutor.schedule({
// Your code logic goes here
}, 3, TimeUnit.SECONDS)
Run Code Online (Sandbox Code Playgroud)
使用后记得关闭executor。
backgroundExecutor.shutdown(); // or backgroundExecutor.shutdownNow();
Run Code Online (Sandbox Code Playgroud)
3 - 在后台线程中执行代码并在主线程上更新 UI。
// Create an executor that executes tasks in the main thread.
val mainExecutor: Executor = ContextCompat.getMainExecutor(this)
// Create an executor that executes tasks in a background thread.
val backgroundExecutor = Executors.newSingleThreadScheduledExecutor()
// Execute a task in the background thread.
backgroundExecutor.execute {
// Your code logic goes here.
// Update UI on the main thread
mainExecutor.execute {
// You code logic goes here.
}
}
Run Code Online (Sandbox Code Playgroud)
调试的最佳性能是什么(如前所述,生产可能会有所不同)? - 执行器和协程基于使用此功能尝试两者需要花费大量时间
fun TestPerformance(){
val startTime = System.nanoTime()
// DEBUG in handler 3002952707
Handler(Looper.getMainLooper()).postDelayed({
val endTime = System.nanoTime()
println("DEBUG in handler ${endTime-startTime}")
}, 3000)
// DEBUG in backgroundExecutor 3001161822
val backgroundExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
backgroundExecutor.schedule({
val endTime = System.nanoTime()
println("DEBUG in backgroundExecutor ${endTime-startTime}")
}, 3, TimeUnit.SECONDS)
// DEBUG in GlobalScope 3046312603
GlobalScope.launch {
delay(3000)
val endTime = System.nanoTime()
println("DEBUG in GlobalScope ${endTime-startTime}")
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我也添加了另一种方式与handler进行比较,并查看代码中的注释,handler和Executor都比Coroutine快,有时handler获胜,有时Executor获胜,两者的性能相同。
如果您想要更多有关如何使用处理程序的示例,请检查此答案,这很有帮助,我在答案中使用了它。
| 归档时间: |
|
| 查看次数: |
332 次 |
| 最近记录: |