Java并发编程:CountDownLatch和Semaphore应用示例

原创 古城微笑少年丶 2024-10-24 12:42 143阅读 0赞

在Java并发编程中,CountDownLatch和Semaphore都是线程同步工具,用于控制多个线程的执行顺序。这里分别给出它们的应用示例:

  1. CountDownLatch:
    CountDownLatch是一个单向共享计数信号。当一个线程调用await方法时,该线程会阻塞直到CountDownLatch的值减少到0。

示例代码:

  1. import java.util.concurrent.CountDownLatch;
  2. public class CountDownLatchExample {
  3. private final CountDownLatch countDownLatch = new CountDownLatch(1);
  4. public void startThread() throws InterruptedException {
  5. countDownLatch.countDown();
  6. System.out.println("Thread 1 started");
  7. // 线程睡眠一段时间,以确保CountDownLatch的值减少
  8. Thread.sleep(2000);
  9. }
  10. public static void main(String[] args) throws InterruptedException {
  11. CountDownLatchExample example = new CountDownLatchExample();
  12. Thread thread1 = new Thread(() -> example.startThread()));
  13. Thread thread2 = new Thread(() -> example.startThread()));
  14. // 启动两个线程
  15. thread1.start();
  16. thread2.start();
  17. // 等待所有线程执行完毕
  18. thread1.join();
  19. thread2.join();
  20. System.out.println("All threads have finished");
  21. }
  22. }

在这个示例中,CountDownLatchExample类有一个countDownLatch。当启动两个线程thread1thread2时,它们会分别调用countDownLatch.countDown()来减少计数器的值。

在主函数中,我们通过Thread.join()等待所有线程执行完毕,然后输出一条消息表示所有任务已经完成。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,143人围观)

还没有评论,来说两句吧...

相关阅读