Java中并发工具类(如Lock, Semaphore等)使用示例

原创 ╰半夏微凉° 2025-03-20 11:33 99阅读 0赞

在Java中,java.util.concurrent.locks.Lockjava.util.concurrent.Semaphore 是常用的并发工具类。下面以这两个类为例,提供使用示例:

  1. 使用Lock进行线程同步
  1. import java.util.concurrent.locks.ReentrantLock;
  2. public class LockExample {
  3. private final ReentrantLock lock = new ReentrantLock();
  4. public void process() throws InterruptedException {
  5. // 获取锁
  6. lock.lock();
  7. try {
  8. // 执行任务,注意这里的代码会被锁定,直到锁被释放
  9. System.out.println("Processing task...");
  10. Thread.sleep(2000); // 假设这个任务需要执行一段时间
  11. // 任务完成后,解锁
  12. lock.unlock();
  13. } catch (Exception e) {
  14. // 锁无法解锁时,解锁并记录异常
  15. try {
  16. lock.unlock(); // 先解锁
  17. e.printStackTrace(); // 再记录异常
  18. } catch (Exception e2) {
  19. // 解锁失败时,记录异常
  20. e2.printStackTrace();
  21. }
  22. }
  23. }
  24. public static void main(String[] args) throws InterruptedException {
  25. LockExample example = new LockExample();
  26. Thread thread1 = new Thread(() -> example.process()));
  27. Thread thread2 = new Thread(() -> example.process()));
  28. // 启动线程
  29. thread1.start();
  30. thread2.start();
  31. // 等待所有线程执行完毕
  32. thread1.join();
  33. thread2.join();
  34. }
  35. }
  1. 使用Semaphore进行资源控制
  1. import java.util.concurrent.Semaphore;
  2. public class SemaphoreExample {
  3. private final Semaphore semaphore = new Semaphore(3); // 初始化,允许的最多等待者数为3
  4. public void process() throws InterruptedException {
  5. // 请求信号量
  6. semaphore.acquire();
  7. try {
  8. System.out.println("Processing task...");
  9. Thread.sleep(2000); // 假设这个任务需要执行一段时间
  10. // 任务完成后,释放信号量
  11. semaphore.release();
  12. } catch (Exception e) {
  13. // 无法获取信号量或释放时出现问题,记录异常并重试
  14. try {
  15. semaphore.release(); // 先尝试释放信号量
  16. e.printStackTrace(); // 再记录异常
  17. } catch (Exception e2) {
  18. // 释放失败时,记录异常
  19. e2.printStackTrace();
  20. }
  21. }
  22. }
  23. public static void main(String[] args) throws InterruptedException {
  24. SemaphoreExample example = new SemaphoreExample();
  25. Thread thread1 = new Thread(() -> example.process()));
  26. Thread thread2 = new Thread(() -> example.process()));
  27. // 启动线程
  28. thread1.start();
  29. thread2.start();
  30. // 等待所有线程执行完毕
  31. thread1.join();
  32. thread2.join();
  33. }
  34. }

这些示例展示了如何使用Lock和Semaphore这两种并发工具类。

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

发表评论

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

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

相关阅读