join方法內部實際是wait方法,不能理解的是 在a執行緒中,b執行緒呼叫了join方法,為什么是a執行緒一直在等待直至b執行緒結束。
uj5u.com熱心網友回復:
老鐵,你最少要吧代碼貼出來啊,不然怎么找問題
uj5u.com熱心網友回復:
你這邏輯描述混亂啊,到底是Thread_A.Join還是Thead_B.Join
看看https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.join?redirectedfrom=MSDN&view=netframework-4.8#System_Threading_Thread_Join
里面
注解寫得很清楚了。
uj5u.com熱心網友回復:
main執行緒呼叫另一個執行緒物件的join方法,為什么會呼叫main會wait(0).public class ThreadTest {
public static void main(String[] args) {
Thread01 t1 = new Thread01();
t1.start();
try {
t1.join(); //在主執行緒中呼叫了t1執行緒的join()方法
} catch (InterruptedException e) {}
for(int i = 0;i < 10;i++) {
System.out.println("in main ");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {}
}
}
}
class Thread01 extends Thread{
public void run() {
for(int i = 0;i < 10;i++) {
System.out.println("in " + Thread.currentThread().getName() + "執行緒" + "i = " + i);
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {}
}
}
}
1在主執行緒中呼叫了t1執行緒的join()方法
而jdk中:
public final void join() throws InterruptedException {
join(0);
}
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;
}
}
}
顯然是呼叫了wait()方法,讓執行緒物件等待。看到這里按理說應該是執行緒物件:t1去等待,怎么反而成了main執行緒等待t1執行完畢?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259069.html
標籤:其他技術討論專區
