Java-并发-12.Thread.join()

  • 线程A执行thread.join(),表示A等待thread线程终止之后才从thread.join()返回
  • join(long millis)和join(long millis, int nanos)使其具有超时特性
    代码示例:
import java.util.concurrent.TimeUnit;

/**
 * 创建10个线程,每个线程等待前一个线程的join()方法,0号线程等待main结束
 *
 * @author pengjunzhe
 */
public class Join {
    public static void main(String[] args) throws InterruptedException {
        Thread previous = Thread.currentThread();
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Domino(previous), String.valueOf(i));
            thread.start();
            previous = thread;
        }
        TimeUnit.SECONDS.sleep(3);
        System.out.println(Thread.currentThread().getName() + " terminate.");
    }

    static class Domino implements Runnable {
        private Thread thread;

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

        @Override
        public void run() {
            try {
                thread.join();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " terminate.");
        }
    }
}

输出结果:

main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.

你可能感兴趣的:(Java-并发-12.Thread.join())