[英]Interrupting active Thread Android
I'm trying to make 2 Threads . 我试图做2个线程 。
Each Thread can interrupt the other one, the two can't be running at the same time . 每个线程都可以中断另一个线程, 这两个线程不能同时运行 。
I've tried to use the function Thread.interrupt(), but this not trigger an exception inside the Thread. 我试图使用函数Thread.interrupt(),但这不会触发Thread内部的异常。
how can I stop a running Thread at any moment? 如何随时停止正在运行的线程? I only found solutions that involve sleeping threads or myths that Thread.Interrupt() trigger an exception, not only a flag.
我只发现了涉及休眠线程或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
}
}
})
Calling Thread.Interrupt()
from outside the thread being stopped it's generally not a good approach to deal with threads, because it can possibly catch the Thread in some intermediate state, dealing with system resources. 从停止的线程外部调用
Thread.Interrupt()
通常不是处理线程的好方法,因为它可能会在某种中间状态捕获Thread,从而处理系统资源。
Better create some variables like isThread1AllowedToRun
and check for its value: 最好创建一些变量,例如
isThread1AllowedToRun
并检查其值:
while (isThread1AllowedToRun) {
...
Thread.sleep(20, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.