开发笔记|多线程按顺序打印输出

如果我们想实现一个这样的功能:每一个线程负责输出一个字母,要求按顺序输出。打个比方,有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"); }

【开发笔记|多线程按顺序打印输出】结果:
开发笔记|多线程按顺序打印输出
文章图片

    推荐阅读