如何控制多线程的顺序执行

Java实现多线程顺序执行的9种方法

目录

1 使用线程的join方法

2 使用主线程的join方法

3 使用对象的wait和notify方法

4 使用单线程的线程池

5 使用AQS的Condition(条件变量)

6 使用CountDownLatch

7 使用CyclicBarrier(回环栅栏)

8 使用Semaphore(信号量)

9 使用CompletableFuture


并发编程的重点:多线程之间的同步,依赖synchornized,wait & notify,AQS和基于Lock的各种实现。
9种方法实现多线程的顺序执行,定义thread1、thread2、thread3,要求执行顺序为:thread1 > thread2 > thread3

1 使用线程的join方法

线程依次join前序执行的线程;

    Thread thread1 = new Thread(
            () -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread1 finished");
            }
    );
    Thread thread2 = new Thread(
            () -> {
                try {
                    thread1.join();
                    Thread.sleep(1000);
                    System.out.println("thread2 finished");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    );
    Thread thread3 = new Thread(
            () -> {
                try {
                    thread2.join();
                    System.out.println("thread3 finished");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    );
    thread3.start();
    thread2.start();
    thread1.start();

2 使用主线程的join方法

        Thread thread1 = new Thread(
                () -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("thread1 finished");
                }
        );
        Thread thread2 = new Thread(
                () -> {
                    try {
                        thread1.join();
                        Thread.sleep(1000);
                        System.out.println("thread2 finished");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        Thread thread3 = new Thread(
                () -> {
                    try {
                        thread2.join();
                        System.out.println("thread3 finished");
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值