多线程同步问题:Java中CountDownLatch、Semaphore用法示例

原创 心已赠人 2024-09-23 07:42 173阅读 0赞

CountDownLatchSemaphore是Java中两种常用的线程同步工具,主要用于控制多个线程的执行顺序。

  1. CountDownLatch示例:
    ```java
    import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
private CountDownLatch countDownLatch = new CountDownLatch(3);

  1. public void threadAction() throws InterruptedException {
  2. System.out.println("Thread-1 starting...");
  3. countDownLatch.await();
  4. System.out.println("Thread-1 completed!");
  5. // Thread 2 and 3 same process
  6. System.out.println("Thread-2 starting...");
  7. countDownLatch.await();
  8. System.out.println("Thread-2 completed!");
  9. System.out.println("Thread-3 starting...");
  10. countDownLatch.await();
  11. System.out.println("Thread-3 completed!");
  12. }
  13. public static void main(String[] args) {
  14. CountDownLatchExample example = new CountDownLatchExample();
  15. Thread thread1 = new Thread(example::threadAction));
  16. Thread thread2 = new Thread(example::threadAction));
  17. Thread thread3 = new Thread(example::threadAction));
  18. thread1.start();
  19. thread2.start();
  20. thread3.start();
  21. }

}

  1. 在这个例子中,我们创建了一个`CountDownLatch`实例,初始计数为3。然后在3个线程中调用`await()`方法,来等待计数器下降到0
  2. 2. `Semaphore`示例:
  3. ```java
  4. import java.util.concurrent.Semaphore;
  5. public class SemaphoreExample {
  6. private Semaphore semaphore = new Semaphore(5); // 初始化允许的最大并发数量为5
  7. public void threadAction() {
  8. try {
  9. semaphore.acquire(); // 请求一个许可证
  10. System.out.println("Thread-1 starting...");
  11. // 线程执行逻辑
  12. Thread.sleep(2000);
  13. System.out.println("Thread-1 completed!");
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. } finally {
  17. semaphore.release(); // 释放一个许可证
  18. }
  19. }
  20. public static void main(String[] args) {
  21. SemaphoreExample example = new SemaphoreExample();
  22. Thread thread1 = new Thread(example::threadAction));
  23. Thread thread2 = new Thread(example::threadAction));
  24. thread1.start();
  25. thread2.start();
  26. }
  27. }

在这个例子中,我们创建了一个Semaphore实例,初始值为5。每个线程请求许可证(调用acquire())时,如果当前许可数量大于0,则允许请求,并减少许可数量;否则线程会阻塞,直到有其他线程释放了许可证。

以上就是Java中CountDownLatch和Semaphore两种同步工具的简单使用示例。

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

发表评论

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

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

相关阅读