线程顺序打印的几种方式

  • 并发编程
小于 1 分钟

1.使用 CountDownLatch

 static CountDownLatch latch = new CountDownLatch(1);

 public static void main(String[] args) throws InterruptedException {
    Thread thread1 = new Thread(() -> {
        System.out.println("A");
        latch.countDown();
    });
    thread1.start();
    latch.await();

    latch = new CountDownLatch(1);
    Thread thread2 = new Thread(() -> {
        System.out.println("B");
        latch.countDown();
    });
    thread2.start();
    latch.await();

    latch = new CountDownLatch(1);
    Thread thread3 = new Thread(() -> {
        System.out.println("C");
        latch.countDown();
    });
    thread3.start();
    latch.await();
}

2.使用CyclicBarrier

static CyclicBarrier barrier = new CyclicBarrier(1);

public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
    Thread thread1 = new Thread(() -> {
        System.out.println("A");
    });
    thread1.start();
    barrier.await();

    barrier.reset();
    Thread thread2 = new Thread(() -> {
        System.out.println("B");
    });
    thread2.start();
    barrier.await();

    barrier.reset();
    Thread thread3 = new Thread(() -> {
        System.out.println("C");
    });
    thread3.start();
    barrier.await();
}

3.使用Semphore

static Semaphore semaphore = new Semaphore(1);

public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
    semaphore.acquire();
    Thread thread1 = new Thread(() -> {
        System.out.println("A");
        semaphore.release();
    });
    thread1.start();

    semaphore.acquire();
    Thread thread2 = new Thread(() -> {
        System.out.println("B");
        semaphore.release();
    });
    thread2.start();

    semaphore.acquire();
    Thread thread3 = new Thread(() -> {
        System.out.println("C");
        semaphore.release();
    });
    thread3.start();
}

4.使用线程池

public static void main(String[] args) {
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    for (int i = 0; i < 3; i++) {
        int finalI = i;
        executorService.submit(() -> {
            System.out.println((char)('A' + finalI));
        });
    }
}
上次编辑于: