Java多线程同步工具:Semaphore与CountDownLatch实践示例

原创 曾经终败给现在 2024-09-27 02:45 136阅读 0赞

Semaphore和CountDownLatch是Java中常用的多线程同步工具。它们主要用来控制同时访问资源的线程数量。

  1. Semaphore(信号量)

Semaphore是一种二值信号机制,它维护一个当前值。当一个工作者试图获取信号量时,如果当前值大于0,那么就减少1,工作者获得信号;否则工作者等待,直到信号量释放。

示例代码:

  1. import java.util.concurrent.Semaphore;
  2. public class SemaphoreExample {
  3. private Semaphore semaphore = new Semaphore(2); // 初始化信号量为2
  4. public void workerThread() throws InterruptedException {
  5. try {
  6. semaphore.acquire(); // 获取信号
  7. System.out.println("Worker " + (threadId++) + " is running ...");
  8. // 工作逻辑
  9. Thread.sleep(3000);
  10. System.out.println("Worker " + (threadId++) + " finished its task ...");
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. } finally {
  14. semaphore.release(); // 释放信号量
  15. }
  16. }
  17. public static void main(String[] args) throws InterruptedException {
  18. SemaphoreExample example = new SemaphoreExample();
  19. for (int i = 0; i < 4; i++) { // 创建4个线程实例
  20. Thread workerThread = new Thread(example::workerThread, "Worker " + (i+1))));
  21. workerThread.start(); // 启动线程
  22. }
  23. }
  24. }
  1. CountDownLatch(计数器)

CountDownLatch是一个特殊的共享变量,它可以被初始化为一个给定的值。当一个工作者需要等待其他工作者完成特定操作后才能开始执行时,可以使用CountDownLatch。

示例代码:

  1. import java.util.concurrent.CountDownLatch;
  2. public class CountDownLatchExample {
  3. private CountDownLatch countDownLatch = new CountDownLatch(2); // 初始化计数器为2
  4. public void workerThread() throws InterruptedException {
  5. try {
  6. countDownLatch.await(); // 等待计数器减少到0
  7. System.out.println("Worker " + (threadId++) + " is running ...");
  8. // 工作逻辑
  9. Thread.sleep(3000);
  10. System.out.println("Worker " + (threadId++) + " finished its task ...");
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. public static void main(String[] args) throws InterruptedException {
  16. CountDownLatchExample example = new CountDownLatchExample();
  17. for (int i = 0; i < 4; i++) { // 创建4个线程实例
  18. Thread workerThread = new Thread(example::workerThread, "Worker " + (i+1))));
  19. workerThread.start(); // 启动线程
  20. }
  21. countDownLatch.countDown(); // 计数器减少到0,表示所有工作已完成
  22. }
  23. }

总结:Semaphore和CountDownLatch都是Java中常用的多线程同步工具。Semaphore用于控制同时访问资源的线程数量,而CountDownLatch则是一个计数器,当一个工作者等待其他工作者完成特定操作后,可以使用CountDownLatch来减少计数,表示工作已完成。

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

发表评论

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

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

相关阅读