ALL is Well!

敏捷是一条很长的路,摸索着前进着

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  30 随笔 :: 23 文章 :: 71 评论 :: 0 Trackbacks

一、在研究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:

 1package wxhx.csdn2;   
 2/**  
 3 *   
 4 * @author bzwm  
 5 *  
 6 */
  
 7class 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}
   
25class 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:(这里只写出修改的部分)

 

 1public 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源码:

 

1public final void join() throws InterruptedException {   
2join(0);   
3}
  

然后进入join(0)方法:

 1   /**  
 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 {   
12long base = System.currentTimeMillis();   
13long now = 0;   
14if (millis < 0{   
15           throw new IllegalArgumentException("timeout value is negative");   
16}
   
17if (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()方法是没有作用的。将直接继续向下执行,这里就不写代码验证了。

----2009年02月12日

posted on 2010-09-01 11:52 李 明 阅读(55988) 评论(16)  编辑  收藏 所属分类: J2SE技术知识

评论

# re: 浅析 Java Thread.join()[未登录] 2011-10-10 10:11 test
二、为什么要用join()方法

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

????????????????????
感觉这段很成问题  回复  更多评论
  

# re: 浅析 Java Thread.join() 2011-10-29 13:25 zhangyou1010
t.start();//线程起动

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

上面这段代码,不会异常啊。  回复  更多评论
  

# re: 浅析 Java Thread.join()[未登录] 2013-03-21 11:37 minelibra
就像主线程是开会一样,会议(主线程)正在进行中,这时候需要一个人join进来(子线程启动),并执行他自己的操作,如果他的操作没有执行完毕,则会议(主线程)不能结束。  回复  更多评论
  

# re: 浅析 Java Thread.join() 2013-05-11 00:05 亿可达西靓
@test
比如:你准备洗澡,需要准备的步骤,准备好衣服,沐浴的东西及烧水这些事情,由于烧水耗时太长,如果也放在主线程之中,就很浪费资源,所以如果我们另开线程去处理,就会达到很好效果,于是乎在准备好衣服,沐浴的东西之前就去开子线程烧水,烧水的过程中主线程准备好衣服,沐浴的东西,此时就等待水烧好,然后方可痛快的洗澡了!!  回复  更多评论
  

# re: 浅析 Java Thread.join() 2013-07-25 14:44 emmet7life
@minelibra
这个解释不错哟  回复  更多评论
  

# re: 浅析 Java Thread.join()[未登录] 2013-09-12 07:08 Mark
这个简单的东西,你搞那么复杂。主线程等待调用join方法的子线程执行结束后再继续执行  回复  更多评论
  

# re: 浅析 Java Thread.join()[未登录] 2013-12-12 10:15 Jack
@Mark
说的对  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-06-12 16:41 11
什么问题?@test
  回复  更多评论
  

# re: 浅析 Java Thread.join()[未登录] 2014-06-17 14:25 YY
你和朋友一起吃饭,突然你肚子痛,要拉屎,这个时候你去了厕所拉屎,拉了很久,但是你的朋友们要等你拉完回来在一起AA  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-06-17 14:30 @YY
精辟  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-06-17 14:35 头很大
@YY
这..... 这个知识点 我懂了  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-08-19 14:31 reiike
麻烦楼主把文章理一理,这么混乱不清还写篇文章,服了。  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-08-19 14:36 reiike

http://www.open-open.com/lib/view/open1371741636171.html

别人的文章,论文章排版,整洁干净,论解释,逻辑清晰,前后连贯。  回复  更多评论
  

# re: 浅析 Java Thread.join() 2014-10-09 09:09 chanedi
@reiike
这两个文章不是一样吗?  回复  更多评论
  

# re: 浅析 Java Thread.join()[未登录] 2014-12-26 16:47 peter
@YY
这个解释口味好重  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: