join()方法如何在多线程中使用

发布时间:2020-12-08 16:24:07 作者:Leah
来源:亿速云 阅读:99

今天就跟大家聊聊有关join()方法如何在多线程中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Thread中,join()方法的作用是调用线程等待该线程完成后,才能继续用下运行。

public class TestThread5 {
  public static void main(String[] args) throws InterruptedException {
    Runner0 run5 = new Runner0();
    Thread th6 = new Thread(run5);
    th6.start();
    th6.join();//join()方法用在此处是为了等待主线程结束后运行子线程
 
    for(int i=0;i<5;i++){
      System.out.println("子线程:"+i);
      }
  }
}
  class Runner0 implements Runnable{
    public void run(){
      for(int i=0;i<5;i++)
        System.out.println("主线程:"+i);
    }
  }

上述代码的运行结构如下所示:

join()方法如何在多线程中使用

当然,如果不使用join()方法

public class TestThread6{
  public static void main(String[] args) throws InterruptedException {
    Runner0 run5 = new Runner0();
    Thread th6 = new Thread(run5);
    th6.start();
//   th6.join();
 
    for(int i=0;i<4;i++){
      System.out.println("子线程:"+i);
      }
  }
}
  class Runner0 implements Runnable{
    public void run(){
      for(int i=0;i<4;i++)
        System.out.println("主线程:"+i);
    }
  }

如上代码注释掉jion()方法,

join()方法如何在多线程中使用

看完上述内容,你们对join()方法如何在多线程中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 导出数据量大的报表内存溢出怎么解决
  2. 在IntelliJ IDEA中多线程并发代码的调试方法详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

多线程 join

上一篇:Android应用中如何对xml进行解析

下一篇:怎么在Java对finalize方法实现禁止

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》