public static synchronized void main(String[] args) throws InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}
- 這種方法的問題是什麼?
- 從現在開始,我該如何避免這些問題?
public static synchronized void main(String[] args) throws InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}
這段代碼有幾個問題。我懷疑你想要寫的東西是這樣的:
public static synchronized void main(String[] args) throws InterruptedException {
System.out.print("X");
Thread.sleep(10000);
System.out.print("Y");
}
的Thread.sleep()
方法將暫停指定的時間間隔當前線程。 Object.wait()
是完全不同的東西,這不太可能是你想要的。
你可以看到我是如何消除線程t
。如果你真的想創建一個單獨的線程,並在該線程上生成打印輸出,那麼你需要給線程做些什麼。要做到這一點,最簡單的方法是重寫線程的run()
方法,並有有線程代碼:
public static synchronized void main(String[] args) {
Thread t = new Thread() {
public void run() {
System.out.print("X");
try { Thread.sleep(10000); } catch (InterruptedException e) { }
System.out.print("Y");
}
};
t.start();
}
書面您的原代碼,其實是創建一個線程,沒有線體,所以當你調用t.start()
空線程只會在後臺啓動,然後立即死亡。
請注意,現在睡眠呼叫已遷移到線程內部,因此我必須爲InterruptedException
添加try/catch子句。 run()
現在不允許拋出異常,不幸的是,我們必須捕捉並忽略異常。
寫這個的另一種方法是在線程t
和主線程中的其餘工作中完成一些工作。這裏有一個如何你可以裂開的工作分成兩個線程的例子:
public static synchronized void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
public void run() {
System.out.print("X");
try { Thread.sleep(10000); } catch (InterruptedException e) { }
}
};
t.start();
t.join();
System.out.print("Y");
}
當這個調用t.join()
它會等待線程執行完,因爲它正在睡覺,這將需要10秒。線程完成後,join()
方法將返回並允許主線程繼續。最終結果將與用戶看起來一樣:程序將打印X,暫停10秒,然後打印Y.
那麼,約翰的建議將做到這一點。但您可能仍然對發生的異常感到模糊。爲此,我希望您閱讀Object.wait()方法和IllegalMonitorStateException的文檔。
閱讀完這些之後,您可能會想到一個問題,Object的監視器到底是什麼。所以這裏是從wikibooks,
每個對象都有一個「對象監視器」。基本上它是一個 '信號量',指示是否 線程正在執行關鍵的 線程代碼。在執行關鍵的 部分之前,線程 必須獲得「對象監視器」。一次只能使用 一個線程可以擁有該對象的顯示器。