我想通過join讓線程 a b c d順序打印,但是現在是亂序打印
public class ExJoin extends Thread {
Thread thread;
public ExJoin(){
}
public ExJoin(Thread thread){
this.thread = thread;
}
@Override
public void run() {
try {
if (thread != null){
thread.join();
}
System.out.println(Thread.currentThread().getName()+" is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread threadA = new ExJoin();
threadA.setName("A");
Thread threadB = new ExJoin(threadA);
threadB.setName("B");
Thread threadC = new ExJoin(threadB);
threadC.setName("C");
Thread threadD = new ExJoin(threadC);
threadD.setName("D");
threadC.start();
threadD.start();
threadA.start();
threadB.start();
}
}
3 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
按照樓主的代碼邏輯,join
是無法做到有序的,因為A/B/C/D
線程的啟動運行依賴于CPU
調度,如果線程B
未啟動線程C
調用threadB.join
方法是不會生效的??梢钥纯?code>jdk內置的邏輯實現isAlive()
為false
時直接返回了。
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
在run
方法中sleep(1000)
確實會順序出現。我猜測可能是指令重排序,前面的線程已經就緒,但是后面的線程對象還沒有創建出來,所以出現了亂序。
添加回答
舉報
0/150
提交
取消