温馨提示×

温馨提示×

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

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

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

发布时间:2020-10-08 08:42:48 来源:脚本之家 阅读:125 作者:lqh 栏目:编程语言

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

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

import java.util.concurrent.TimeUnit;

/**
 * 6-13
 */
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.
 

向AI问一下细节

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

AI