java线程学习之join方法

 join()方法表示一个线程要加入另一个线程,直到被加入的线程执行完毕。

这个概念不好理解的话看面这个例子

 1 public class TestJoin {
 2   public static void main(String[] args) {
 3     MyThread2 t1 = new MyThread2("ceshi");
 4     t1.start();
 5     try {
 6         t1.join(); //执行到这个方法时,主线程会等着t1线程执行结束才会继续执行
 7         System.out.println("t1线程是否死亡"+t1.isAlive());//此时t1线程已经执行完毕终止掉了
 8     } catch (InterruptedException e) {}
 9         
10     for(int i=1;i<=10;i++){
11       System.out.println("i am main thread");
12     }
13   }
14 }
15 class MyThread2 extends Thread {
16   MyThread2(String s){
17       super(s);
18   }
19   
20   public void run(){
21     for(int i =1;i<=10;i++){
22       System.out.println("i am "+getName());
23       try {
24           sleep(1000);
25       } catch (InterruptedException e) {
26           return;
27       }
28     }
29   }
30 }

上面这个例子是已开始有主线程main,然后创建了个 t1 线程 ti线程调用了join方法。就把线程主线程暂停了等待着  t1 线程执行完毕,等 t1 线程执行结束后,t1线程终止。主线程main继续执行直至结束。

执行结果为:

join的本质是让调用线程wait()在当前线程实例上

因为jdk实现join的代码为

 

 1 public final synchronized void join(long millis)
 2     throws InterruptedException {
 3         long base = System.currentTimeMillis();
 4         long now = 0;
 5 
 6         if (millis < 0) {
 7             throw new IllegalArgumentException("timeout value is negative");
 8         }
 9 
10         if (millis == 0) {
11             while (isAlive()) {
12                 wait(0);
13             }
14         } else {
15             while (isAlive()) {
16                 long delay = millis - now;
17                 if (delay <= 0) {
18                     break;
19                 }
20                 wait(delay);
21                 now = System.currentTimeMillis() - base;
22             }
23         }
24     }
jdk的join(long millis)方法

 里面核心的代码片段为:

join的三种用法

    join() 等待该线程终止。正如上面所介绍

   join(long millis)等待该线程终止的时间最长为 millis 毫秒。这个会等待被加入的线程执行 millis多毫秒,等待结束后,线程一起运行。将上面举的例子修改一下

     将 t1.join(); 替换成 t1.join(3000);

join(long millis,int nanos) 等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。 其余的和  join(long millis)一样。
三种方式如果被打断的话都会抛出 InterruptedException异常。

猜你喜欢

转载自www.cnblogs.com/songlove/p/10632958.html