实现三个线程A、B、C顺序执行

1. 题目

通过锁或其他方式实现三个线程顺序执行

2. 思路

2.1. 思路一,join()

使用Thread的join()方法,join()方法可以实现等待某个线程执行完毕后,再执行后续代码。三个线程A、B、C,A执行的时候不等待,B执行的时候等待A,C执行的时候等待B。即可实现A、B、C三个线程顺序执行。

2.2. 思路二,CompletableFuture

使用CompletableFuture实现线程任务的编排。

3. 代码实现

使用 join() 实现三个线程顺序执行

public class rt01 {
    public static void main(String[] args) {
        Thread A = new Thread(new Work(null), "A");
        Thread B = new Thread(new Work(A), "B");
        Thread C = new Thread(new Work(B), "C");
        A.start();
        B.start();
        C.start();
    }

    static class Work implements Runnable{
        private final Thread beforeThread;

        public Work(Thread beforeThread) {
            this.beforeThread = beforeThread;
        }

        @Override
        public void run() {
            if(beforeThread != null){
                try {
                    beforeThread.join();  // join() 等待beforeThread线程执行完毕,再继续执行
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println(Thread.currentThread().getName());
            }
        }
    }
}

使用CompletableFuture实现三个线程顺序执行

public class rt02 {
    public static void main(String[] args) {
        Thread A = new Thread(new Work(), "A");
        Thread B = new Thread(new Work(), "B");
        Thread C = new Thread(new Work(), "C");
        CompletableFuture.runAsync(A::start)
                .thenRun(B::start)
                .thenRun(C::start);
    }

    static class Work implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
}

4. 参考链接

https://developer.aliyun.com/article/868129

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kyrielx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值