栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于多线程中join()的用法实例讲解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于多线程中join()的用法实例讲解

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

public class TestThread5 {
  public static void main(String[] args) throws InterruptedException {
    Runner0 run5 = new Runner0();
    Thread th5 = new Thread(run5);
    th5.start();
    th5.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()方法

public class TestThread6{
  public static void main(String[] args) throws InterruptedException {
    Runner0 run5 = new Runner0();
    Thread th5 = new Thread(run5);
    th5.start();
//   th5.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()的用法实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/143807.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号