打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

线程加入

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.

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
关于多线程的个人理解
Java Thread.join()
thread.join()用法及例子
深入浅出Java多线程(1)-方法 join
线程 Join方法:将某个子线程合并到主线程,即等子线程全部运行全部执行完之后才执行主线程...
并发编程之:CountDownLatch
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服