歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 多線程之--- Thread.join介紹

Java 多線程之--- Thread.join介紹

日期:2017/3/1 9:39:53   编辑:Linux編程

這次說的是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;

/**
* 數據源
* @author bird
* 2014年9月15日 下午10:10:04
*/
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) {
// TODO Auto-generated catch block
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多線程從簡單到復雜 http://www.linuxidc.com/Linux/2014-07/104435.htm

Java多線程經典案例 http://www.linuxidc.com/Linux/2014-06/103458.htm

Java多線程:ReentrantReadWriteLock讀寫鎖的使用 http://www.linuxidc.com/Linux/2014-06/103457.htm

Java內存映射文件實現多線程下載 http://www.linuxidc.com/Linux/2014-05/102201.htm

Java多線程:一道阿裡面試題的分析與應對 http://www.linuxidc.com/Linux/2014-03/98715.htm

Java中兩種實現多線程方式的對比分析 http://www.linuxidc.com/Linux/2013-12/93690.htm

Copyright © Linux教程網 All Rights Reserved