Java并发编程实战:CountDownLatch与Semaphore应用实例

原创 £神魔★判官ぃ 2024-12-11 21:09 95阅读 0赞

CountDownLatchSemaphore是Java并发库中常用的两种控制共享资源的工具。以下是它们的应用实例:

  1. CountDownLatch:

    • 作用:当一个或多个线程完成他们的任务后,可以通过调用countDown()方法来通知其他的等待的线程。
    • 示例:

      1. CountDownLatch latch = new CountDownLatch(3);
      2. // 线程1执行任务并计数
      3. Thread t1 = new Thread(() -> {
      4. try {
      5. latch.countDown();
      6. System.out.println("Task 1 done by " + Thread.currentThread().getName());
      7. } catch (Exception e) {
      8. e.printStackTrace();
      9. }
      10. }));
      11. // 线程2和3执行任务并计数
      12. Thread t2 = new Thread(() -> {
      13. try {
      14. latch.countDown();
      15. System.out.println("Task 2 done by " + Thread.currentThread().getName());
      16. } catch (Exception e) {
      17. e.printStackTrace();
      18. }
      19. }));
      20. Thread t3 = new Thread(() -> {
      21. try {
      22. latch.countDown();
      23. System.out.println("Task 3 done by " + Thread.currentThread().getName());
      24. } catch (Exception e) {
      25. e.printStackTrace();
      26. }
      27. }));
      28. // 启动线程
      29. t1.start();
      30. t2.start();
      31. t3.start();
      32. // 等待所有线程执行完毕,然后关闭CountDownLatch
      33. try {
      34. latch.await();
      35. System.out.println("All tasks done by " + Thread.currentThread().getName());
      36. } catch (InterruptedException e) {
      37. e.printStackTrace();
      38. }
  2. Semaphore:

    • 作用:Semaphore是一种信号量,它用于控制同时访问共享资源的线程数量。当一个线程需要访问资源时,它可以尝试获取信号量;如果信号量已经达到了最大值(默认为1),那么当前线程将被阻塞,直到其他线程释放了信号量。
    • 示例:

      1. // 创建一个容量为1的Semaphore
      2. Semaphore semaphore = new Semaphore(1);
      3. // 线程A,需要访问资源,尝试获取信号量
      4. Thread tA = new Thread(() -> {
      5. try {
      6. semaphore.acquire();
      7. System.out.println("Thread A got resource by " + Thread.currentThread().getName());
      8. } catch (Exception e) {
      9. e.printStackTrace();
      10. }
      11. }));
      12. // 线程B,不需要访问资源,直接释放信号量
      13. Thread tB = new Thread(() -> {
      14. try {
      15. semaphore.release();
      16. System.out.println("Thread B released resource by " + Thread.currentThread().getName());
      17. } catch (Exception e) {
      18. e.printStackTrace();
      19. }
      20. }));
      21. // 启动线程
      22. tA.start();
      23. tB.start();
      24. // 等待所有线程执行完毕,然后关闭Semaphore
      25. try {
      26. semaphore.awaitUninterruptibly(); // 耐心等待信号量释放
      27. System.out.println("All tasks done by " + Thread.currentThread().getName());
      28. } catch (InterruptedException e) {
      29. e.printStackTrace();
      30. }

以上就是CountDownLatchSemaphore在Java并发编程中的基本应用实例。

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

发表评论

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

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

相关阅读