我使用while循環知道什麼時候該停止應用程序,我使用了線程的執行服務:While循環使用線程不會停止
ExecutorService executorService = Executors.newFixedThreadPool(8);
String[] error = {""};
while(!(error[0].equals("Nothing found"))) {
executorService.execute(new Runnable() {
@Override
public void run() {
addProductsToSet();
//rest of the code
synchronized (error[0]) {
error[0] = // code that might return "Nothing found" to stop the while loop
}
//rest of the code
} //end of run method
});
}
executorService.shutdown();
while(!executorService.isTerminated()) {
}
,我的問題是在於error[0]
有值「找不到」,但代碼不會停止。它永遠持續下去。如果我不使用線程,則while循環停止。我也嘗試executorService.shutdownNow()
,但不起作用。
有什麼建議嗎?
您是否嘗試使'error'變量易變? – Eran
永遠不要寫一個旋轉循環。我強烈建議你用'executorService.awaitTermination(Long.MAX_VALUE,TimeUnit.MILLISECONDS)'替換'while(!executorService.isTerminated())',就像[ExecutorService的文檔。shutdown()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--)建議。 – VGR