這次談談 Thread 的 join 方法。以前總是用 run 和 sleep,這兩個比較清楚;而 join 的主要功能是:當你在一個方法裡調用其他線程時,若使用 thread1.join(),當前調用的線程就會一直等待 thread1 返回,直到 thread1 的 run 方法執行完畢返回,主線程才會繼續往下執行。
join 還有帶參數的重載形式,參數含義是:先等待該線程調用完,例如 thread1.sleep(1000),主線程會等待 thread1 運行,直到 thread1 執行完返回,或當前主線程等待超過 1 秒鐘就不再理會 thread1,繼續往下執行。
程式碼如下:
package com.bird.concursey;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class DataSourceLoader implements Runnable{
public void run() {
System.out.println("begining the data source loding" + new Date());
try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("begining the data source loding" + new Date());
}
public static void main(String[] args) {
DataSourceLoader dsLoader = new DataSourceLoader();
Thread thread1 = new Thread(dsLoader, "dsloader");
NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
Thread thread2 = new Thread(ncLoader, "ncloader");
thread1.start();
thread2.start();
try {
thread1.join();
// thread2.join(1000);
} catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(new Date());
}
}
package com.bird.concursey;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class NetworkConnectionsLoader implements Runnable {
public void run() {
System.out.println("begining the data source loding" + new Date());
try { TimeUnit.SECONDS.sleep(6); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("begining the data source loding" + new Date());
}
}
運行結果:
begining the data source lodingMon Sep 15 22:27:41 CST 2014
begining the data source lodingMon Sep 15 22:27:41 CST 2014
begining the data source lodingMon Sep 15 22:27:45 CST 2014
Mon Sep 15 22:27:46 CST 2014
begining the data source lodingMon Sep 15 22:27:47 CST 2014
延伸閱讀:Java 多線程從簡單到復雜 https://www.linuxidc.com/Linux/2014-07/104435.htm |Java 多線程經典案例 https://www.linuxidc.com/Linux/2014-06/103458.htm |Java 多線程:ReentrantReadWriteLock 讀寫鎖的使用 https://www.linuxidc.com/Linux/2014-06/103457.htm |Java 內存映射文件實現多線程下載 https://www.linuxidc.com/Linux/2014-05/102201.htm |Java 多線程:一道阿裡面試題的分析與應對 https://www.linuxidc.com/Linux/2014-03/98715.htm |Java 中兩種實現多線程方式的對比分析 https://www.linuxidc.com/Linux/2013-12/93690.htm