多线程按顺序打印输出

如果我们想实现一个这样的功能:每一个线程负责输出一个字母,要求按顺序输出。打个比方,有3个线程,线程A线程B、线程C,分别输出A、B、C,最终打印结果希望是按顺序输出,即ABC

要实现这个有两个方案,可以利用Thread的join方法或者java.util.concurrent.CountDownLatch类来实现。

第一种:join

public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("A");
        });

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

        thread1.join();
        thread2.start();

        thread2.join();
        System.out.println("C");

    }

结果:
在这里插入图片描述
第二种:CountDownLatch

 public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("A");
            countDownLatch.countDown();
        }, "A").start();

        countDownLatch.await();
        CountDownLatch countDownLatch2 = new CountDownLatch(1);
        new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B");
            countDownLatch2.countDown();
        }, "B").start();

        countDownLatch2.await();
        System.out.println("C");
    }

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值