[Linux#43][线程] 死锁 | 同步 | 基于 BlockingQueue 的生产者消费者模型
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerWithBlockingQueue {
private final BlockingQueue<String> queue;
public ProducerConsumerWithBlockingQueue() {
this.queue = new LinkedBlockingQueue<>();
}
public void start() throws InterruptedException {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
producerThread.join();
consumerThread.join();
}
private class Producer implements Runnable {
@Override
public void run() {
try {
queue.put("Item");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private class Consumer implements Runnable {
@Override
public void run() {
try {
String item = queue.take();
System.out.println("Consumed: " + item);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
ProducerConsumerWithBlockingQueue example = new ProducerConsumerWithBlockingQueue();
try {
example.start();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
这段代码展示了如何使用BlockingQueue
来避免死锁。Producer
向队列中放入一个项目,而Consumer
从队列中取出一个项目并打印。如果队列为空,take
方法会阻塞等待直到有项目可用。如果队列满,put
方法会阻塞等待直到队列中有空间。这样,生产者和消费者之间通过队列进行同步,避免了直接同步导致的死锁问题。
评论已关闭