请详细解释Java中的线程同步机制,以及Condition类在实现线程同步中的具体应用场景。

线程同步是Java多线程编程中重要的机制之一,用于协调多个线程对共享资源的访问,避免数据不一致或竞态条件的发生。Java中提供了多种线程同步机制,例如 synchronized 关键字、ReentrantLock 类、Semaphore 类等。Condition 类是 ReentrantLock 提供的一个工具,用于更细粒度的线程控制,允许线程在特定条件下等待或被唤醒。

一、线程同步机制

  1. synchronized 关键字

    • 用于修饰方法或代码块,确保同一时间只有一个线程可以执行被修饰的代码。
    • 示例:
      public class Counter {
          private int count = 0;
          public synchronized void increment() {
              count++;
          }
      }
      
      在这个例子中,increment 方法通过 synchronized 关键字保证了线程安全。
  2. 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 更多的控制功能。
  3. 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 提供的线程协调工具,允许线程在某个条件下等待或被唤醒,常用于生产者-消费者模型或类似场景。

  1. 生产者-消费者模型

    • 示例:
      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 对象,分别用于控制缓冲区不满和不空的条件下线程的等待与唤醒。
  2. 多条件等待

    • 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 提供了更灵活的控制能力,尤其适合复杂场景。通过合理使用这些机制,可以确保线程安全并优化性能。