亲宝软件园·资讯

展开

java Thread.join() java 中Thread.join()如何使用

人气:1
想了解java 中Thread.join()怎样使用的相关内容吗,在本文为您仔细讲解java Thread.join()的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,Thread.join(),java,Thread.join()用法详解,java,Thread.join()实例,下面大家一起来学习吧。

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.
 

加载全部内容

相关教程
猜你喜欢
用户评论