Thread.join()方法控制线程的执行顺序

Thread类join()方法重载了3次.分别是

join()throws InterruptedException;  //无参数的join()等价于join(0),作用是一直等待该线程死亡

join(long millis, int nanos) throws InterruptedException;  //最多等待该线程死亡millis毫秒

join(long millis, int nanos) throws InterruptedException ; //最多等待该线程死亡millis毫秒加nanos纳秒

join()的作用,java doc 说明:Waits for this thread to die.等待这个线程死亡,如果join的线程不死亡,程序就会阻塞在那里.

package com.qd.thread.join;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenlongbo on 2017/5/26.
 */
public class ThreadjoinTest {

    public static class RunableJob implements Runnable{
        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + " start: " + new Date());
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
                System.out.println(thread.getName() + " end: " + new Date());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    
    public static void main(String[] args) throws InterruptedException {
        RunableJob job = new RunableJob();
        Thread t1 = new Thread(job,"T1");
        Thread t2 = new Thread(job,"T2");
        Thread t3 = new Thread(job,"T3");
        Thread t4 = new Thread(job,"T4");
        Thread t5 = new Thread(job,"T5");
        t4.start();
        t4.join();
        t5.start();
        t5.join();
        t3.start();
        t3.join();
        t2.start();
        t2.join();
        t1.start();
    }


}

程序的执行结果:

T4 start: Fri May 26 17:20:29 CST 2017
T4 end: Fri May 26 17:20:31 CST 2017
T5 start: Fri May 26 17:20:31 CST 2017
T5 end: Fri May 26 17:20:33 CST 2017
T3 start: Fri May 26 17:20:33 CST 2017
T3 end: Fri May 26 17:20:35 CST 2017
T2 start: Fri May 26 17:20:35 CST 2017
T2 end: Fri May 26 17:20:37 CST 2017
T1 start: Fri May 26 17:20:37 CST 2017
T1 end: Fri May 26 17:20:39 CST 2017

Process finished with exit code 0

原文地址:https://www.cnblogs.com/cbySense/p/6909619.html