根据文档,我们无法从后台线程更新UI。但就我而言,我可以更新UI而不出现任何问题。检查线程3。我还打印了线程名称,结果是Thread-4。
为什么从后台线程访问主线程时不抛出异常?
fun threadsWithThreadPoolExecutor(v: View) {
val startTime = System.currentTimeMillis()
var endTime: Long = startTime
val threadPoolExecutor = Executors.newFixedThreadPool(3)
val thread1 = Thread(Runnable {
Thread.sleep(7000)
endTime = System.currentTimeMillis()
})
val thread2 = Thread(Runnable {
Thread.sleep(10000)
endTime = System.currentTimeMillis()
})
val thread3 = Thread(Runnable {
Thread.sleep(3000)
endTime = System.currentTimeMillis()
tv_result.text = "This is from thread"
})
showProcessRunning()
threadPoolExecutor.submit(thread1)
threadPoolExecutor.submit(thread2)
threadPoolExecutor.submit(thread3)
Log.d("MyLog", thread3.name)
Handler().postDelayed(Runnable {
showTotalTime(startTime, endTime)
}, 20000)
}
更新 正如评论中提到的那样,我为什么在ThreadPoolExecutor#submit()中传递线程,因为它实现了Runnable。另外,如果我不使用ThreadPool,那么问题仍然存在。
fun threadsWithoutExecutor(v: View) {
val startTime = System.currentTimeMillis()
var endTime: Long = startTime
val thread1 = Thread(Runnable {
Thread.sleep(7000)
endTime = System.currentTimeMillis()
})
val thread2 = Thread(Runnable {
Thread.sleep(10000)
endTime = System.currentTimeMillis()
})
val thread3 = Thread(Runnable {
tv_result.text = "sdadadasda"
Thread.sleep(3000)
endTime = System.currentTimeMillis()
})
thread3.priority = Thread.MIN_PRIORITY
showProcessRunning()
thread1.start()
thread2.start()
thread3.start()
Thread(Runnable {
thread1.join()
thread2.join()
thread3.join()
showTotalTime(startTime, endTime)
}).start()
}