深入解析Java中的并发工具:Lock和Condition示例

原创 红太狼 2024-10-13 14:03 165阅读 0赞

在Java中,LockCondition是两个重要的并发工具,分别用于管理共享资源的访问权限以及线程之间的通信。

  1. Lock(锁):
  • ReentrantLock:这是最常用的锁实现,它提供了可重入、公平竞争等特性。
  • 使用示例:
    ```java
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
private final Lock lock = new ReentrantLock();

  1. public void lockResource() {
  2. try {
  3. lock.lock();
  4. System.out.println("Resource locked.");
  5. } catch (InterruptedException e) {
  6. // Handle interruption
  7. e.printStackTrace();
  8. } finally {
  9. // Always unlock
  10. try {
  11. lock.unlock();
  12. System.out.println("Resource unlocked.");
  13. } catch (Exception e) {
  14. // Handle any exception while unlocking
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. public static void main(String[] args) {
  20. LockExample example = new LockExample();
  21. example.lockResource(); // Acquire the lock
  22. Thread.sleep(500); // Let other threads execute
  23. example.lockResource(); // Try to acquire again, should fail due to lock held
  24. }

}

  1. 2. Condition(条件):
  2. - `Condition`:它是`Lock`的一部分,用于在锁定共享资源的同时进行线程间的通信。
  3. - 使用示例:
  4. ```java
  5. import java.util.concurrent.locks.Condition;
  6. import java.util.concurrent.locks.Lock;
  7. import java.util.concurrent.locks.ReentrantLock;
  8. public class ConditionExample {
  9. private final Lock lock = new ReentrantLock();
  10. private final Condition condition = lock.newCondition();
  11. public void signal() {
  12. lock.lock();
  13. try {
  14. condition.signalAll(); // Notify all waiting threads
  15. System.out.println("Signaled.");
  16. } finally {
  17. lock.unlock();
  18. }
  19. }
  20. public void await() throws InterruptedException {
  21. lock.lock();
  22. try {
  23. condition.await(); // Wait until notified or timeout occurs
  24. System.out.println("Awoken.");
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. } finally {
  28. lock.unlock();
  29. }
  30. }
  31. public static void main(String[] args) {
  32. ConditionExample example = new ConditionExample();
  33. example.signal(); // Notify all waiting threads
  34. Thread.sleep(500); // Let other threads execute
  35. example.await(); // Wait until notified or timeout occurs
  36. }
  37. }

以上代码展示了如何使用LockCondition来管理线程的并发访问。

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

发表评论

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

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

相关阅读