[英]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.