2017-04-17 58 views
3

我正在嘗試創建一個runnable,它將測試以查看您是否已經死亡(低於1的健康狀況),如果您死了,則會停止可運行。如果你不是,它會繼續下去。但我找不到停止可運行的方法。有什麼方法可以用腳本停止可運行的runnable?如何停止可運行內的可運行?

注意,可運行正在通過一個線程中運行:

Thread thread1 = new Thread(runnableName); 
thread1.start(); 

Runnable的實例:

Runnable r1 = new Runnable() { 
    public void run() { 
     while (true) { 
      if (health < 1) { 
       // How do i stop the runnable? 
      } 
     } 
    } 
} 
+4

你不必做任何特殊的事情,只要到達'run'方法的末尾,線程就會終止。 – Welbog

+0

檢查是否已死的腳本處於while循環。 – Potato

+3

因此退出while循環。 – Welbog

回答

1

可以打破循環,如果健康< 1:

if (health < 1) { 
    break; 
} 

或者你可以改變條件:

while (health > 1) { 

} 
0
while (true) { 
    if (health < 1) { 
     // How do i stop the runnable? 
     return; 
    } 
}