深入解析Java中的并发工具:Lock和Condition示例
在Java中,Lock
和Condition
是两个重要的并发工具,分别用于管理共享资源的访问权限以及线程之间的通信。
- Lock(锁):
ReentrantLock
:这是最常用的锁实现,它提供了可重入、公平竞争等特性。- 使用示例:
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private final Lock lock = new ReentrantLock();
public void lockResource() {
try {
lock.lock();
System.out.println("Resource locked.");
} catch (InterruptedException e) {
// Handle interruption
e.printStackTrace();
} finally {
// Always unlock
try {
lock.unlock();
System.out.println("Resource unlocked.");
} catch (Exception e) {
// Handle any exception while unlocking
e.printStackTrace();
}
}
}
public static void main(String[] args) {
LockExample example = new LockExample();
example.lockResource(); // Acquire the lock
Thread.sleep(500); // Let other threads execute
example.lockResource(); // Try to acquire again, should fail due to lock held
}
}
2. Condition(条件):
- `Condition`:它是`Lock`的一部分,用于在锁定共享资源的同时进行线程间的通信。
- 使用示例:
```java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionExample {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void signal() {
lock.lock();
try {
condition.signalAll(); // Notify all waiting threads
System.out.println("Signaled.");
} finally {
lock.unlock();
}
}
public void await() throws InterruptedException {
lock.lock();
try {
condition.await(); // Wait until notified or timeout occurs
System.out.println("Awoken.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ConditionExample example = new ConditionExample();
example.signal(); // Notify all waiting threads
Thread.sleep(500); // Let other threads execute
example.await(); // Wait until notified or timeout occurs
}
}
以上代码展示了如何使用Lock
和Condition
来管理线程的并发访问。
还没有评论,来说两句吧...