多執行緒中的join方法的含義

2021-08-28 13:11:54 字數 980 閱讀 2335

public class worker   catch (exception e)

list1.add(random.nextint(100));    }}

public void stagetwo() catch (exception e)

list2.add(random.nextint(100));    }}

public void process()

}public void main()

};thread t2=new thread()

};t1.start();

t2.start();

try catch (exception e)

long end=system.currenttimemillis();

system.out.println("list1  "+list1.size()+"list2  "+list2.size());

system.out.println(end-start);}}

join的意思是連線,加入的意思

main是主線程,在main中建立了thread執行緒,在main中呼叫了thread.join(),那麼等thread結束後再執行main**。

在很多情況下,主線程生成並起動了子執行緒,如果子執行緒裡要進行大量的耗時的運算,主線程往往將於子執行緒之前結束,但是如果主線程處理完其他的事務後,需要用到子執行緒的處理結果,也就是主線程需要等待子執行緒執行完成之後再結束,這個時候就要用到join()方法了。

如果上述**不加join方法,則main方法不會等待執行緒執行完,就會執行後面的列印操作 得到的資料

list1  0list2  0

0「等待該執行緒終止。」

解釋一下,是主線程(我在「一」裡已經命名過了)等待子執行緒的終止。也就是在子執行緒呼叫了join()方法後面的**,只有等到子執行緒結束了才能執行。(waits for this thread to die.)

多執行緒中的join 方法

直接看 package net.csdn.demo01 public class mythread extends thread package net.csdn.demo01 public class testmythread 執行結果 張三 1張三 2張三 3張三 4張三 5張三 6張三 7張三...

多執行緒Join方法

天意憐幽草,人間重晩晴 a.sleep 5000 讓執行緒睡5秒但是,如果你不知道執行緒b需要執行多長時間,並且在a中需要使用到b中的結果,那麼,這時你就可以使用join方法 下面是具體的例子 可以看到,join long time 方法內部其實是呼叫了wait long time 方法,我們了解到...

多執行緒join 方法

直接 public static void main string args for thread t list int n 0 for thread t list catch interruptedexception e system.out.println 完全結束 static class m...