保证线程的执行顺序

41 阅读1分钟

1.利用单个线程的线程池

@Test
public void test01(){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(()->{
        System.out.println("任务1");
    });
    executorService.submit(()->{
        System.out.println("任务2");
    });
    executorService.submit(()->{
        System.out.println("任务3");
    });
}

2.利用Thread.join方法

@Test
public void test02(){
    Thread thread1 = new Thread(() -> {
        System.out.println("任务1");
    });
    Thread thread2 = new Thread(() -> {
        try {
            thread1.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("任务2");
    });
    Thread thread3 = new Thread(() -> {
        try {
            thread2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("任务3");
    });
    thread1.start();
    thread2.start();
    thread3.start();
}

3.利用CountDownLatch

@Test
public void test03(){
    CountDownLatch countDownLatch2 = new CountDownLatch(1);
    CountDownLatch countDownLatch3 = new CountDownLatch(1);
    Thread thread1 = new Thread(() -> {
        countDownLatch2.countDown();
        System.out.println("任务1");
    });
    Thread thread2 = new Thread(() -> {
        try {
            countDownLatch2.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("任务2");
        countDownLatch3.countDown();
    });
    Thread thread3 = new Thread(() -> {
        try {
            countDownLatch3.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("任务3");
    });
    thread1.start();
    thread2.start();
    thread3.start();
}