生产者消费者Java代码实现
时间: 2024-02-23 14:53:32 浏览: 91
以下是使用Java中的BlockingQueue实现生产者消费者模型的代码示例:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
Thread producer = new Thread(new Producer(queue));
Thread consumer = new Thread(new Consumer(queue));
producer.start();
consumer.start();
}
}
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
queue.put(i);
System.out.println("生产者生产了:" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
int num = queue.take();
System.out.println("消费者消费了:" + num);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
以上代码中,我们使用了Java中的BlockingQueue实现了生产者消费者模型。BlockingQueue是一个线程安全的队列,它提供了put()和take()方法,分别用于向队列中添加元素和从队列中取出元素。当队列已满时,put()方法会阻塞生产者线程,直到队列中有空闲位置;当队列为空时,take()方法会阻塞消费者线程,直到队列中有元素。