请详细解释Java中的线程同步机制,以及Condition类在实现线程同步中的具体应用场景。
线程同步是Java多线程编程中重要的机制之一,用于协调多个线程对共享资源的访问,避免数据不一致或竞态条件的发生。Java中提供了多种线程同步机制,例如 synchronized 关键字、ReentrantLock 类、Semaphore 类等。Condition 类是 ReentrantLock 提供的一个工具,用于更细粒度的线程控制,允许线程在特定条件下等待或被唤醒。
一、线程同步机制
-
synchronized关键字- 用于修饰方法或代码块,确保同一时间只有一个线程可以执行被修饰的代码。
- 示例:
在这个例子中,public class Counter { private int count = 0; public synchronized void increment() { count++; } }increment方法通过synchronized关键字保证了线程安全。
-
ReentrantLock类- 提供了比
synchronized更灵活的锁机制,支持公平锁和非公平锁。 - 示例:
通过显式地加锁和释放锁,public class Counter { private final ReentrantLock lock = new ReentrantLock(); private int count = 0; public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } }ReentrantLock提供了比synchronized更多的控制功能。
- 提供了比
-
Semaphore类- 用于控制对资源的访问数量。
- 示例:
public class ResourcePool { private final Semaphore semaphore; public ResourcePool(int permits) { semaphore = new Semaphore(permits); } public void useResource() throws InterruptedException { semaphore.acquire(); try { // 使用资源 } finally { semaphore.release(); } } }Semaphore限制了同时访问资源的线程数量。
二、Condition 类的应用场景
Condition 类是 ReentrantLock 提供的线程协调工具,允许线程在某个条件下等待或被唤醒,常用于生产者-消费者模型或类似场景。
-
生产者-消费者模型
- 示例:
在这个例子中,public class Buffer { private final ReentrantLock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); private final Queue<Integer> queue = new LinkedList<>(); private final int capacity; public Buffer(int capacity) { this.capacity = capacity; } public void put(int value) throws InterruptedException { lock.lock(); try { while (queue.size() == capacity) { notFull.await(); } queue.add(value); notEmpty.signalAll(); } finally { lock.unlock(); } } public int take() throws InterruptedException { lock.lock(); try { while (queue.isEmpty()) { notEmpty.await(); } int value = queue.poll(); notFull.signalAll(); return value; } finally { lock.unlock(); } } }notFull和notEmpty是两个Condition对象,分别用于控制缓冲区不满和不空的条件下线程的等待与唤醒。
- 示例:
-
多条件等待
Condition还支持为同一个锁创建多个条件,实现更复杂的等待唤醒机制。- 示例:
public class TaskQueue { private final ReentrantLock lock = new ReentrantLock(); private final Condition lowPriority = lock.newCondition(); private final Condition highPriority = lock.newCondition(); // 实现高优先级和低优先级任务的处理逻辑 }
总结
线程同步机制是Java多线程编程中的核心部分,synchronized 适用于简单的同步需求,而 ReentrantLock 和 Condition 提供了更灵活的控制能力,尤其适合复杂场景。通过合理使用这些机制,可以确保线程安全并优化性能。