Android 能够更新UI窗体线程。为什么?

Android 能够更新UI窗体线程。为什么?,android,multithreading,threadpool,Android,Multithreading,Threadpool,根据文档,我们无法从后台线程更新UI。但在我的情况下,我能够更新用户界面没有任何问题。检查螺纹3。我还打印了线程名称,结果是线程4 为什么从后台线程访问主线程时不会引发异常 fun threadsWithThreadPoolExecutor(v: View) { val startTime = System.currentTimeMillis() var endTime: Long = startTime val threadPoolExecutor = Executor

根据文档,我们无法从后台线程更新UI。但在我的情况下,我能够更新用户界面没有任何问题。检查螺纹3。我还打印了线程名称,结果是线程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()
}

你在使用Android Kotlin扩展吗?你能分享完整的代码吗?你等了20秒了吗?当你到达
tv\u结果时,它一定会崩溃。text
你在哪个设备和操作系统上运行,因为当我尝试上述代码时,应用程序会在3秒钟后崩溃。我没有使用任何kotlin扩展是的,我等待了1分钟,没有出现异常情况