在Java中同步三个生产者线程和一个消费者线程,通常需要使用线程同步机制来确保生产者和消费者之间的协调工作。下面是一个简单的示例代码,展示了如何使用synchronized
关键字和wait()
/notifyAll()
方法来实现这一目标。
wait()
使当前线程等待,notifyAll()
唤醒所有等待的线程。import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumerExample {
private static final int MAX_SIZE = 10;
private final Queue<Integer> queue = new LinkedList<>();
public static void main(String[] args) {
ProducerConsumerExample example = new ProducerConsumerExample();
for (int i = 0; i < 3; i++) {
new Thread(example.new Producer()).start();
}
new Thread(example.new Consumer()).start();
}
class Producer implements Runnable {
private int item = 0;
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == MAX_SIZE) {
try {
queue.wait(); // 队列满时等待
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
queue.add(item++);
System.out.println("Produced: " + item);
queue.notifyAll(); // 通知消费者线程
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait(); // 队列空时等待
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
int item = queue.poll();
System.out.println("Consumed: " + item);
queue.notifyAll(); // 通知生产者线程
}
}
}
}
}
LinkedList
作为共享队列,存储生产者生产的数据。synchronized
关键字确保对队列的访问是线程安全的。wait()
方法使生产者线程等待。notifyAll()
方法唤醒所有等待的线程(包括消费者线程)。synchronized
关键字确保对队列的访问是线程安全的。wait()
方法使消费者线程等待。notifyAll()
方法唤醒所有等待的线程(包括生产者线程)。wait()
方法之前已经获得了对象的锁,并且在适当的时候调用notifyAll()
方法。while
循环而不是if
语句来检查条件,以防止虚假唤醒。InterruptedException
时,重新设置线程的中断状态,以便其他代码可以检测到中断。通过上述方法,可以实现三个生产者线程和一个消费者线程的同步工作。
领取专属 10元无门槛券
手把手带您无忧上云