写一个三个线程顺序打印abc(多种方法,countdownlatch,线程池,completelyablefuture)

1 个回答

  • 凤鸣
    无论什么关系,我看不到我想要的态度。我就不会给你想要的细节。
    要实现三个线程顺序打印 `a`, `b`, `c`,可以通过多种方式来实现,如 `CountDownLatch`、`线程池`、`CompletableFuture` 等。以下是三种不同的实现方法: ### 1. 使用 `CountDownLatch` 实现 `CountDownLatch` 可以用于控制线程的执行顺序。通过使用三个 `CountDownLatch` 实现线程按顺序打印。 ```java import java.util.concurrent.CountDownLatch; public class PrintABCWithCountDownLatch { public static void main(String[] args) { CountDownLatch latchA = new CountDownLatch(0); // 开始时让A直接执行 CountDownLatch latchB = new CountDownLatch(1); CountDownLatch latchC = new CountDownLatch(1); Thread threadA = new Thread(() -> { try { latchA.await(); // 等待计数为0 System.out.print("A"); latchB.countDown(); // A完成后让B可以执行 } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadB = new Thread(() -> { try { latchB.await(); System.out.print("B"); latchC.countDown(); // B完成后让C可以执行 } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadC = new Thread(() -> { try { latchC.await(); System.out.print("C"); } catch (InterruptedException e) { e.printStackTrace(); } }); threadA.start(); threadB.start(); threadC.start(); } } ``` ### 2. 使用 `线程池` 实现 通过使用线程池中的 `ExecutorService` 提交任务,并利用信号机制保证线程的执行顺序。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class PrintABCWithThreadPool { public static void main(String[] args) { Semaphore semaphoreA = new Semaphore(1); Semaphore semaphoreB = new Semaphore(0); Semaphore semaphoreC = new Semaphore(0); ExecutorService executorService = Executors.newFixedThreadPool(3); executorService.submit(() -> { try { semaphoreA.acquire(); System.out.print("A"); semaphoreB.release(); } catch (InterruptedException e) { e.printStackTrace(); } }); executorService.submit(() -> { try { semaphoreB.acquire(); System.out.print("B"); semaphoreC.release(); } catch (InterruptedException e) { e.printStackTrace(); } }); executorService.submit(() -> { try { semaphoreC.acquire(); System.out.print("C"); } catch (InterruptedException e) { e.printStackTrace(); } }); executorService.shutdown(); } } ``` ### 3. 使用 `CompletableFuture` 实现 `CompletableFuture` 提供了一种异步编程的方式,可以通过它来控制任务的执行顺序。 ```java import java.util.concurrent.CompletableFuture; public class PrintABCWithCompletableFuture { public static void main(String[] args) { CompletableFuture<Void> futureA = CompletableFuture.runAsync(() -> { System.out.print("A"); }); CompletableFuture<Void> futureB = futureA.thenRunAsync(() -> { System.out.print("B"); }); CompletableFuture<Void> futureC = futureB.thenRunAsync(() -> { System.out.print("C"); }); futureC.join(); // 等待所有任务完成 } } ``` ### 总结 这三种方法都可以实现线程的顺序执行: 1. **`CountDownLatch`**:通过计数器来控制多个线程的同步,非常适合等待某些事件发生之后再开始操作。 2. **`线程池`**:配合 `Semaphore` 实现信号机制,能够灵活控制线程之间的依赖关系。 3. **`CompletableFuture`**:基于异步的任务编排方式,能够更简洁地实现任务的顺序执行。 你可以根据具体场景选择适合的实现方式。
    发布于 2024-10-21 14:40 •IP属地 内蒙古
    举报
    评论
    收藏