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

java 中Thread.join()的使用方法

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

java 中Thread.join()的使用方法

java 中Thread.join()的使用方法

如果一个线程A执行了thread.join()语句,其含义是:当前线程A等待thread线程终止之后才从thread.join()返回。

import java.util.concurrent.TimeUnit;


public class Join {
 public static void main(String[] args) throws Exception {
  Thread previous = Thread.currentThread();
  for (int i = 0; i < 10; i++) {
   // 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
   Thread thread = new Thread(new Domino(previous), String.valueOf(i));
   thread.start();
   previous = thread;
  }

  TimeUnit.SECONDS.sleep(5);
  System.out.println(Thread.currentThread().getName() + " terminate.");
 }

 static class Domino implements Runnable {
  private Thread thread;

  public Domino(Thread thread) {
   this.thread = thread;
  }

  public void run() {
   try {
    thread.join();
   } catch (InterruptedException e) {
   }
   System.out.println(Thread.currentThread().getName() + " terminate.");
  }
 }
}

执行结果:

main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.
 

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

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

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