1
我的一個Runnable接口的運行下面的代碼:如何終止空無限循環線程不使用使用Thread.stop
while(true) {}
我已經試過包裝該Runnable在執行程序的API,然後試圖關機方法。嘗試thread.interrupt。但沒有任何工作。我無法修改Runnable代碼。任何建議...
我的一個Runnable接口的運行下面的代碼:如何終止空無限循環線程不使用使用Thread.stop
while(true) {}
我已經試過包裝該Runnable在執行程序的API,然後試圖關機方法。嘗試thread.interrupt。但沒有任何工作。我無法修改Runnable代碼。任何建議...
檢查其中斷標誌:
while (!Thread.currentThread().isInterrupted()) {}
大多數執行人的中斷對shutdownNow
工作線程,所以這給你一個乾淨關閉整潔的機制。
如果您需要在Executor
的上下文之外終止Runnable
,則需要爲其設置一個shutdown
方法來設置標誌。
final AtomicBoolean isShutdown = new AtomicBoolean();
public void shutdown() {
if (!isShutdown.compareAndSet(false, true)) {
throw new IllegalStateException();
}
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !isShutdown.get()) {}
}
基本上不這樣做。無論如何,你應該避免終止這樣的線程 - 給你的runnable一個標誌來定期檢查。 –
你是對的。但是,無論如何終止這樣的線程,而不使用其停止方法。 –
如果線程沒有設置爲允許取消(即不想查看它是否應該終止),那麼停止它的唯一方法是中止它。所以,正如Jon Skeet所說,「不要那樣做。」 –