现在有 T1、T2、T3 三个线程,你怎样保证 T2 在 T1 执行完后执行,T3 在 T2 执行完 后执行

使用 Thread.join()

public class ThreadJoin {

    public static void main(String[] args) throws InterruptedException {


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 2; i ++) {
                System.out.println("t1 - " + i);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 2; i ++) {
                System.out.println("t2- " + i);
            }
        });
        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 2; i ++) {
                System.out.println("t3 - " + i);
            }
        });

        t1.start();
        t1.join();

        t2.start();
        t2.join();

        t3.start();
        t3.join();
    }

}

使用 volatile

利用线程间可见性

public class ThreadJoin {


    private static volatile int id = -1;

    public static void main(String[] args) throws InterruptedException {


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 2; i ++) {
                System.out.println("t1 - " + i);
            }
            id = 2;
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                if (id == 2) {
                    for (int i = 0; i < 2; i ++) {
                        System.out.println("t2- " + i);
                    }
                    id = 3;
                    break;
                }
                Thread.yield();
            }
        });
        Thread t3 = new Thread(() -> {
            while (true) {
                if (id == 3) {
                    for (int i = 0; i < 2; i ++) {
                        System.out.println("t3 - " + i);
                    }
                    break;
                }
                Thread.yield();
            }
        });
        id = 1;
        t1.start();
        t2.start();
        t3.start();
    }

}

你可能感兴趣的:(现在有 T1、T2、T3 三个线程,你怎样保证 T2 在 T1 执行完后执行,T3 在 T2 执行完 后执行)