【发布时间】:2018-02-22 17:00:25
【问题描述】:
我正在尝试制作 2 线程。
每个线程都可以中断另一个,两者不能同时运行。
我尝试使用函数 Thread.interrupt(),但这不会触发 Thread 内部的异常。
如何随时停止正在运行的线程?我只找到了涉及休眠线程或 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
}
}
})
【问题讨论】:
-
interrupt() 如果没有调用低级阻塞方法,则会设置一个标志。 ibm.com/developerworks/library/j-jtp05236
标签: java android multithreading kotlin interrupt