码迷,mamicode.com
首页 > 编程语言 > 详细

浅析 Java Thread.join()

时间:2016-03-04 15:56:26      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

一、在研究join的用法之前,先明确两件事情。

1.join方法定义在Thread类中,则调用者必须是一个线程,

例如:

Thread t = new CustomThread();//这里一般是自定义的线程类

t.start();//线程起动

t.join();//此处会抛出InterruptedException异常

 

2.上面的两行代码也是在一个线程里面执行的。

 

以上出现了两个线程,一个是我们自定义的线程类,我们实现了run方法,做一些我们需要的工作;另外一个线程,生成我们自定义线程类的对象,然后执行

customThread.start();

customThread.join();

在这种情况下,两个线程的关系是一个线程由另外一个线程生成并起动,所以我们暂且认为第一个线程叫做“子线程”,另外一个线程叫做“主线程”。

 

二、为什么要用join()方法

主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算(这里可以借鉴下线程的作用),当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。

 

 

三、join方法的作用

在网上看到有人说“将两个线程合并”。这样解释我觉得理解起来还更麻烦。不如就借鉴下API里的说法:

“等待该线程终止。”

解释一下,是主线程(我在“一”里已经命名过了)等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。(Waits for this thread to die.)

 

 

四、用实例来理解

写一个简单的例子来看一下join()的用法,一共三个类:

1.CustomThread 类

2. CustomThread1类

3. JoinTestDemo 类,main方法所在的类。

 

代码1:

package wxhx.csdn2;   
 2技术分享/**  
 3技术分享 *   
 4技术分享 * @author bzwm  
 5技术分享 *  
 6技术分享 */  
 7技术分享class CustomThread1 extends Thread {   
 8技术分享    public CustomThread1() {   
 9技术分享        super("[CustomThread1] Thread");   
10技术分享    };   
11技术分享    public void run() {   
12技术分享        String threadName = Thread.currentThread().getName();   
13技术分享        System.out.println(threadName + " start.");   
14技术分享        try {   
15技术分享            for (int i = 0; i < 5; i++{   
16技术分享                System.out.println(threadName + " loop at " + i);   
17技术分享                Thread.sleep(1000);   
18技术分享            }   
19技术分享            System.out.println(threadName + " end.");   
20技术分享        } catch (Exception e) {   
21技术分享            System.out.println("Exception from " + threadName + ".run");   
22技术分享        }   
23技术分享    }   
24技术分享}   
25技术分享class CustomThread extends Thread {   
26技术分享    CustomThread1 t1;   
27技术分享    public CustomThread(CustomThread1 t1) {   
28技术分享        super("[CustomThread] Thread");   
29技术分享        this.t1 = t1;   
30技术分享    }   
31技术分享    public void run() {   
32技术分享        String threadName = Thread.currentThread().getName();   
33技术分享        System.out.println(threadName + " start.");   
34技术分享        try {    35            t1.join();    36            System.out.println(threadName + " end.");    37        } catch (Exception e) {    38            System.out.println("Exception from " + threadName + ".run");    39        }    40    }    41}    42public class JoinTestDemo {    43    public static void main(String[] args) {    44        String threadName = Thread.currentThread().getName();    45        System.out.println(threadName + " start.");    46        CustomThread1 t1 = new CustomThread1();    47        CustomThread t = new CustomThread(t1);    48        try {    49            t1.start();    50            Thread.sleep(2000);    51            t.start();    52            t.join();//在代碼2里,將此處注釋掉    53        } catch (Exception e) {    54            System.out.println("Exception from main");    55        }    56        System.out.println(threadName + " end!");    57    }    58}


打印结果:

 

main start.//main方法所在的线程起动,但没有马上结束,因为调用t.join();,所以要等到t结束了,此线程才能向下执行。

[CustomThread1] Thread start.//线程CustomThread1起动

[CustomThread1] Thread loop at 0//线程CustomThread1执行

[CustomThread1] Thread loop at 1//线程CustomThread1执行

[CustomThread] Thread start.//线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。

[CustomThread1] Thread loop at 2//线程CustomThread1继续执行

[CustomThread1] Thread loop at 3//线程CustomThread1继续执行

[CustomThread1] Thread loop at 4//线程CustomThread1继续执行

[CustomThread1] Thread end. //线程CustomThread1结束了

[CustomThread] Thread end.// 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

main end!//线程CustomThread结束,此线程在t.join();阻塞处起动,向下继续执行的结果。

 

修改一下代码,得到代码2:(这里只写出修改的部分)

 

public class JoinTestDemo {   
 2技术分享    public static void main(String[] args) {   
 3技术分享        String threadName = Thread.currentThread().getName();   
 4技术分享        System.out.println(threadName + " start.");   
 5技术分享        CustomThread1 t1 = new CustomThread1();   
 6技术分享        CustomThread t = new CustomThread(t1);   
 7技术分享        try {   
 8技术分享            t1.start();   
 9技术分享            Thread.sleep(2000);   
10技术分享            t.start();   
11技术分享//          t.join();//在代碼2里,將此處注釋掉   
12技术分享        } catch (Exception e) {   
13技术分享            System.out.println("Exception from main");   
14技术分享        }   
15技术分享        System.out.println(threadName + " end!");   
16技术分享    }   
17技术分享}


打印结果:

 

main start. // main方法所在的线程起动,但没有马上结束,这里并不是因为join方法,而是因为Thread.sleep(2000);

[CustomThread1] Thread start. //线程CustomThread1起动

[CustomThread1] Thread loop at 0//线程CustomThread1执行

[CustomThread1] Thread loop at 1//线程CustomThread1执行

main end!// Thread.sleep(2000);结束,虽然在线程CustomThread执行了t1.join();,但这并不会影响到其他线程(这里main方法所在的线程)。

[CustomThread] Thread start. //线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。

[CustomThread1] Thread loop at 2//线程CustomThread1继续执行

[CustomThread1] Thread loop at 3//线程CustomThread1继续执行

[CustomThread1] Thread loop at 4//线程CustomThread1继续执行

[CustomThread1] Thread end. //线程CustomThread1结束了

[CustomThread] Thread end. // 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

 

 

五、从源码看join()方法

 

在CustomThread的run方法里,执行了t1.join();,进入看一下它的JDK源码:

 

final void join() throws InterruptedException {   
2技术分享join(0);   
3技术分享}  

 

然后进入join(0)方法:

   /**  
 2技术分享    * Waits at most <code>millis</code> milliseconds for this thread to   
 3技术分享    * die. A timeout of <code>0</code> means to wait forever. //注意这句  
 4技术分享    *  
 5技术分享    * @param      millis   the time to wait in milliseconds.  
 6技术分享    * @exception  InterruptedException if another thread has interrupted  
 7技术分享    *             the current thread.  The <i>interrupted status</i> of the  
 8技术分享    *             current thread is cleared when this exception is thrown.  
 9技术分享    */  
10技术分享   public final synchronized void join(long millis) //参数millis为0.   
11技术分享   throws InterruptedException {   
12技术分享long base = System.currentTimeMillis();   
13技术分享long now = 0;   
14技术分享if (millis < 0{   
15技术分享           throw new IllegalArgumentException("timeout value is negative");   
16技术分享}   
17技术分享if (millis == 0{//进入这个分支   
18技术分享    while (isAlive()) {//判断本线程是否为活动的。这里的本线程就是t1.   
19技术分享    wait(0);//阻塞   
20技术分享    }   
21技术分享} else {   
22技术分享    while (isAlive()) {   
23技术分享    long delay = millis - now;   
24技术分享    if (delay <= 0{   
25技术分享        break;   
26技术分享    }   
27技术分享    wait(delay);   
28技术分享    now = System.currentTimeMillis() - base;   
29技术分享    }   
30技术分享}   
31技术分享   } 

 

单纯从代码上看,如果线程被生成了,但还未被起动,调用它的join()方法是没有作用的。将直接继续向下执行,这里就不写代码验证了。

浅析 Java Thread.join()

标签:

原文地址:http://www.cnblogs.com/kabi/p/5242093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!