在多线程编程的世界里,线程间的有效通信是构建高性能、高并发系统的关键所在。Java作为主流的开发语言,提供了丰富的线程间通信机制,使得程序员能够更好地驾驭并行计算,优化程序性能。本文将深入解读Java中几种关键的线程间通信方式——wait/notify机制、条件变量Condition,以及一些高级并发工具类如CountDownLatch、Semaphore和CyclicBarrier,并结合实际应用场景进行详尽的代码解析。
1.wait/notify机制
Java中的Object类提供了wait()和notify()/notifyAll()方法,它们是实现线程间通信的基础手段。当一个线程调用对象的wait()方法时,该线程会释放对象锁并进入等待状态,直到其他线程调用同一对象的notify()或notifyAll()方法唤醒它。下面是一个简单的生产者-消费者模型的代码示例:
public class Buffer {
private int count = 0;
private final int capacity;
public Buffer(int capacity) {
this.capacity = capacity;
}
public synchronized void put(int num) throws InterruptedException {
while (count == capacity) {
wait();
}
// 生产数据
count++;
System.out.println("生产者: " + num);
notify(); // 唤醒等待的消费者线程
}
public synchronized void take() throws InterruptedException {
while (count == 0) {
wait();
}
// 消费数据
count--;
System.out.println("消费者: " + count);
notify(); // 唤醒等待的生产者线程
}
public static void main(String[] args) {
Buffer buffer = new Buffer(5); // 创建容量为5的缓冲区
// 创建生产者线程
Thread producerThread = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
try {
buffer.put(i); // 生产数据
Thread.sleep(100); // 模拟生产间隔时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产者");
// 创建消费者线程
Thread consumerThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
buffer.take(); // 消费数据
Thread.sleep(100); // 模拟消费间隔时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费者");
// 启动生产者和消费者线程
producerThread.start();
consumerThread.start();
// 确保主线程等待生产者和消费者线程都结束
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
如果不启动消费者,生产者就会生产到创建容量和进行等待消费
2.条件变量Condition
Java.util.concurrent.locks包下的Condition接口提供了一种更为灵活的线程等待/通知机制。通过Lock接口的newCondition()方法可以创建Condition对象,然后使用await()、signal()和signalAll()方法进行线程间通信。相比传统的wait/notify,Condition能精确控制哪些线程被唤醒。
public class Buffer2 {
private int count = 0;
private final int capacity;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public Buffer2(int capacity) {
this.capacity = capacity;
}
public void put(int num) throws InterruptedException {
lock.lock();
try {
while (count == capacity) {
notFull.await();
}
// 生产数据
count++;
System.out.println("生产者: " + num);
notEmpty.signal(); // 唤醒等待的消费者线程
} finally {
lock.unlock();
}
}
public void take() throws InterruptedException {
lock.lock();
try {
while (count == 0) {
notEmpty.await();
}
// 消费数据
count--;
System.out.println("消费者: " + count);
notFull.signal(); // 唤醒等待的生产者线程
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Buffer buffer = new Buffer(5);
Thread producerThread = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
try {
buffer.put(i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产者");
Thread consumerThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
buffer.take();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费者");
producerThread.start();
consumerThread.start();
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.高级并发工具类
CountDownLatch:
主要用于确保某个任务完成前,其他所有线程都被阻塞。例如,在启动多个线程执行预热任务后,主线程需等待所有子线程完成后才能继续执行:
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
// 设置线程数量
int N = 5;
// 初始化一个CountDownLatch,初始值为N,表示需要等待N个线程完成
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
// 创建并启动N个线程
for (int i = 0; i < N; ++i) {
new Thread(() -> {
try {
// 线程等待开始信号
startSignal.await();
// 执行任务(此处以打印信息和休眠模拟任务)
System.out.println(Thread.currentThread().getName() + " 开始执行...");
Thread.sleep(1000); // 模拟耗时任务
System.out.println(Thread.currentThread().getName() + " 执行完毕...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 任务完成后,计数器减一
doneSignal.countDown();
}
}, "Worker-" + i).start();
}
// 主线程发出开始信号
System.out.println("主线程开始工作...");
startSignal.countDown();
// 主线程等待所有子线程完成
System.out.println("主线程执行完毕:开始等待子线程执行...");
doneSignal.await();
System.out.println("所有线程都执行完毕.");
}
}
Semaphore:信号量
用于限制同时访问特定资源的线程数量,常用于流量控制:
public class ProducerConsumerDemo {
private static final Semaphore semaphore = new Semaphore(5); // 最大并发数为5
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
semaphore.acquire(); // 获取许可,若当前许可数大于0,则获取并减少1;否则等待
System.out.println(Thread.currentThread().getName() + "进入了临界区,当前可用许可数:" + semaphore.availablePermits());
// 在这里模拟访问共享资源的操作
accessSharedResource();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
} finally {
semaphore.release(); // 访问完毕后,释放许可,增加1
System.out.println(Thread.currentThread().getName() + "离开了临界区,当前可用许可数:" + semaphore.availablePermits());
}
}, "Thread-" + i).start();
}
}
private static void accessSharedResource() {
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + "正在访问共享资源...");
}
}
CyclicBarrier:循环栅栏
用于让一组线程在某个屏障点上互相等待,直到所有线程都到达栅栏点才会继续执行:
public class ProducerConsumerDemo {
public static void main(String[] args) {
// 创建一个CyclicBarrier,参数3表示需要3个线程同时到达屏障
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("所有线程都到达了屏障,现在一起进行下一步.");
});
// 创建并启动3个线程
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
// 模拟线程执行任务
simulateTask(i);
// 当任务完成时,线程到达屏障
barrier.await();
// 这里是所有线程到达屏障后一起执行的代码
System.out.println("Thread " + Thread.currentThread().getName() + " has passed the barrier and is continuing with the next task.");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "Thread-" + i).start();
}
}
// 模拟线程执行的任务
private static void simulateTask(int taskId) {
System.out.println("Thread " + Thread.currentThread().getName() + " (Task ID: " + taskId + ") starts its task.");
try {
Thread.sleep(500); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
理解并掌握Java中的线程间通信机制,无论是基础的wait/notify,还是更灵活的Condition,或是强大的并发工具类,都将有助于我们设计出更高效、稳定的多线程程序。实战中,不断磨练并发编程技巧,善用各种并发工具,方能在纷繁复杂的并发世界中游刃有余。