我有一個簡單的(或者至少我認爲它是)在線程中執行某些工作的Java應用程序。Java線程無法啓動(或需要很長時間才能啓動)
是這樣的:
public class Task implements Runnable {
public boolean running = false;
public void run() {
running = true;
// long running processing
}
}
...
void startTask() {
Task task = new Task();
Thread thread = new Thread(task);
thread.start();
// I added this thinking the calling thread might terminate before
// the new thread starts
while (!task.running) {
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
// log error
}
}
startTask()
以上被稱爲響應於REST請求(這是一個Spring啓動應用程序)。它在我的開發機器(Windows 10,Oracle JDK)和Amazon EC2實例(Amazon Linux,OpenJDK)上運行良好,但不在Google Compute實例(Ubuntu 16.04,OpenJDK)上運行。在後一種情況下,工作線程永遠不會啓動(task.running
永遠不會設置爲true
),或者它有時在60+秒後啓動。我很困惑。
鑑於任務本身不是很複雜(再加上設置「運行」標誌是它的第一件事情,而這從來沒有發生)的事實導致我認爲這是一個奇怪的JVM /系統相關問題,但我真的不知道。
最令人沮喪的是它的工作有時(通常是我第一次上傳/運行它重建後)。並且從未在我的電腦上工作過。
編輯:我曾嘗試在Ubuntu中使用Oracle JRE,但同樣缺乏成功。
2nd編輯:是的,我在這裏寫了示例代碼時犯了一些錯誤。固定。
你是對的。我在示例代碼中犯了一個錯誤 - 我編輯了這個問題,現在它匹配我的實際代碼(它應該調用'thread.start()') – bobsyouruncle