Java中的join

You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1
and thread T3 run after T2?

你有三个线程T1,T2,T3,如何使得T1执行完后再执行T2,T2执行完后再执行T3?

以下是一个可能的实现方法:

public class ThreadJoin implements Runnable {

    private final Thread joinTarget;
    public ThreadJoin(Thread joinTarget) {
        this.joinTarget = joinTarget;
    }

    @Override
    public void run() {
        if(joinTarget != null) {
            try {
                joinTarget.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("Join complete " + Thread.currentThread().getName());
        }
    }

    private static class MyThread implements Runnable {
        @Override
        public void run() {
            System.out.println("MyThread");
        }
    }    

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyThread(), "Thread1");
        Thread t2 = new Thread(new ThreadJoin(t1), "Thread2");
        Thread t3 = new Thread(new ThreadJoin(t2), "Thread3");
        t1.start();
        t2.start();
        t3.start();
    }
}