分享

Java多线程(2):线程加入/join()

 米老鼠的世界 2021-03-03

线程加入

join()方法,等待其他线程终止。在当前线程(主线程)中调用另一个线程(子线程)的join()方法,则当前线程转入阻塞状态,直到另一个线程运行结束,当前线程再由阻塞转为就绪状态

也就是主线程中,子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。

 

在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束。

如下例子:

复制代码
 1 class JoinRunnable implements Runnable {
 2     @Override
 3     public void run() {
 4         System.out.println("Child thread start.");
 5         try {
 6             for (int i = 1; i <= 5; i++) {
 7                 System.out.println("Child thread runing [" + i + "].");
 8                 Thread.sleep((int) (Math.random() * 100));
 9             }
10         } catch (InterruptedException e) {
11             System.out.println("Child thread interrupted.");
12         }
13         System.out.println("Child thread end.");
14     }
15 }
16 
17 public class JoinDemo {
18     // main是主线程
19     public static void main(String args[]) {
20         System.out.println("Main thread start.");
21         new Thread(new JoinRunnable()).start();
22         System.out.println("Main thread end.");
23     }
24 }
复制代码

执行结果:

复制代码
Main thread start.
Main thread end.
Child thread start.
Child thread runing [1].
Child thread runing [2].
Child thread runing [3].
Child thread runing [4].
Child thread runing [5].
Child thread end.
复制代码

 

如果主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。

如下例子:

复制代码
 1 class JoinRunnable implements Runnable {
 2     @Override
 3     public void run() {
 4         System.out.println("Child thread start.");
 5         try {
 6             for (int i = 1; i <= 5; i++) {
 7                 System.out.println("Child thread runing [" + i + "].");
 8                 Thread.sleep((int) (Math.random() * 100));
 9             }
10         } catch (InterruptedException e) {
11             System.out.println("Child thread interrupted.");
12         }
13         System.out.println("Child thread end.");
14     }
15 }
16 
17 public class JoinDemo {
18     // main是主线程
19     public static void main(String args[]) {
20         System.out.println("Main thread start.");
21         Thread t = new Thread(new JoinRunnable());
22         t.start();
23         try {
24             t.join();
25         } catch (InterruptedException e) {
26             e.printStackTrace();
27         }
28         System.out.println("Main thread end.");
29     }
30 }
复制代码

执行结果:

复制代码
Main thread start.
Child thread start.
Child thread runing [1].
Child thread runing [2].
Child thread runing [3].
Child thread runing [4].
Child thread runing [5].
Child thread end.
Main thread end.
复制代码

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多