[英]Interrupting active Thread Android
我试图做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
}
}
})
从停止的线程外部调用Thread.Interrupt()
通常不是处理线程的好方法,因为它可能会在某种中间状态捕获Thread,从而处理系统资源。
最好创建一些变量,例如isThread1AllowedToRun
并检查其值:
while (isThread1AllowedToRun) {
...
Thread.sleep(20, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.