中断活动线程 Android

Interrupting active Thread Android

我正在尝试创建 2 个线程

每个线程都可以打断另一个,两者不能运行同时.

我试过使用函数Thread.interrupt(),但这并没有触发线程内部的异常。

如何随时停止 运行 线程?我只找到涉及休眠线程的解决方案或 Thread.Interrupt() 触发异常的神话,而不仅仅是一个标志。

val toTransparent: Thread = (object : java.lang.Thread() {
    override fun run() {
        try {
            if (toOpaque.isAlive)
                toOpaque.interrupt()
            while (opacity > 0) {
                sleep(1)
                activityForUI.runOnUiThread() {
                    searchBarEmpresa_linearLayout.background.alpha = opacity
                }
                opacity--
            }
        } catch (e: InterruptedException) {
            Thread.currentThread().interrupt()
            return
        }
    }
})

val toOpaque: Thread = (object : Thread() {
    override fun run() {
        try {
            if (toTransparent.isAlive)
                toTransparent.interrupt()
            while (opacity < 255) {
                sleep(1)
                activityForUI.runOnUiThread() {
                    searchBarEmpresa_linearLayout.background.alpha = opacity
                }
                opacity++
            }
        } catch (e: InterruptedException) {
            Thread.currentThread().interrupt()
            return
        }
    }
})

从正在停止的线程外部调用 Thread.Interrupt() 通常不是处理线程的好方法,因为它可能会捕获处于某个中间状态的线程,处理系统资源。

最好创建一些变量,例如 isThread1AllowedToRun 并检查其值:

while (isThread1AllowedToRun) {
    ...
    Thread.sleep(20, 0);
}