[英]Java - Thread join() and order of execution SCJP question?
我一直在為O / SCJP考試做一些練習。 考慮以下代碼:
public class Cruiser implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Cruiser());
a.start();
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run() {
System.out.print("Run");
}
}
資料來源: http : //scjptest.com/mock-test.xhtml
該站點指出輸出(其模擬問題的答案)將為BeginRunEnd
並且在正常運行該類時,這正是輸出。
但是,在調試時,輸出為RunBeginEnd
。
它是公平地說, 正常執行下,輸出將始終 BeginRunEnd
或者將這個取決於其他因素(如新的線程類是多么沉重 /多久開始需要加入它的線程之后)?
您會說這是一個公平/准確的考試問題嗎?
我認為BeginRunEnd比RunBeginEnd更有可能 (我希望實際啟動新線程的過程要花一會兒才能進入run
方法,並且讓第一個線程先進入打印,然后再用盡它的內存。時間片(在大多數情況下是時間片),但是在編程時假定它是錯誤的 。
您應該在調用start
就將這兩個線程視為完全獨立,直到它們通過join
調用再次明確地捆綁在一起。 從邏輯上講,新線程可以一直運行到完成,直到主線程打印“開始”為止。
對我來說似乎是一個壞問題。
這是一個垃圾問題。 沒有同步,結果是不確定的。
這真的是bofa fida SCJP問題,還是僅僅是某個試圖出售SCJP培訓的網站所提出的問題? 如果是后者,那么我會避免像瘟疫那樣的地點。
這可能取決於平台,但是為了顯示順序可以更改。
public class Cruiser implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Cruiser());
a.setPriority(Thread.MAX_PRIORITY);
a.start();
// Thread.sleep(1);
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run() {
System.out.print("Run");
}
}
第一次運行時打印。
RunBeginEnd
但是之后主要是BeginRunEnd
如果線程停止,即使持續1 ms,它將幾乎每次都生成RunBeginEnd。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.