java 多線程join,合并線程用法

來源:互聯網
上載者:User

線程的join合并的含義就是將幾個並行線程的線程合并為一個單線程執行,應用情境是當一個線程必須等待另一個線程執行完畢才能執行時可以使用join方法。

 代碼如下 複製代碼
package com.javaer.thread;
 
public class Tjoin {
 
/**
 * @param args
 */
public static void main(String[] args) {
Thread t = new Thread(new Runner());
t.start();
try {
t.join(1000);
System.out.println("join ok");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
 
}
 
}
 
}
 
class Runner implements Runnable {
 
@Override
public void run() {
try {
System.out.println("Start sleep");
Thread.sleep(1000);
   System.out.println("End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
 
}
}
Start sleep
join ok
End sleep

主線程等待1000ms,進行合并,跳回主線程,然後執行子線程

如果將

t.join(1000);
改為

t.join(2000);
主線程等待2000ms,進行合并。

結果

Start sleep
End sleep
join ok
主線程等2000,開始join。 跳回主線程,發現子線程都執行完畢了。

如果改成

t.join(0)
JDK這樣說的 A timeout of 0 means to wait forever 字面意思是永遠等待.

結果

Start sleep
End sleep
join ok
其實Join方法實現是通過wait。 當main線程調用t.join時候,main線程會獲得線程對象t的鎖(wait 意味著拿到該對象的鎖),調用該對象的wait(等待時間),直到該對象喚醒main線程,比如退出後。

所以上面的t.join(0) 等到子線程退出以後,跳回主線程。

main 線程調用t.join時,必須能夠拿到線程t對象的鎖,如果拿不到它是無法wait的,剛開的例子t.join(1000)不是說明了main線程等待1秒,如果在它等待之前,其他線程擷取了t對象的鎖,它等待時間可不就是1秒了

 代碼如下 複製代碼

 
package com.javaer.thread;
 
public class Tjoin {
/**
 * @param args
 */
public static void main(String[] args) {
Thread t = new Thread(new Runner());
new Threader(t).start();
t.start();
try {
t.join(1000);
System.out.println("join ok");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
 
class Threader extends Thread {
Thread thread;
public Threader(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
holdThreadLock();
}
public void holdThreadLock() {
synchronized (thread) {
System.out.println("擷取一個鎖");
try {
Thread.sleep(9000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("釋放鎖");
}
}
}
 
class Runner implements Runnable {
 
@Override
public void run() {
try {
System.out.println("Start sleep");
Thread.sleep(2000);
System.out.println("End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

擷取一個鎖
Start sleep
End sleep
釋放鎖
join ok
一個線程擷取了鎖,主線在join的時候,即使被join的線程結束了,因為線程被鎖住,所以即使join的時間也到了,但是還是必須等待鎖釋放,才能被join

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.