用java多线程实现消费者生产者问题
时间: 2023-05-20 15:01:13 浏览: 370
可以使用Java中的BlockingQueue来实现消费者生产者问题。BlockingQueue是一个线程安全的队列,它提供了put()和take()方法,分别用于生产和消费。当队列为空时,take()方法会阻塞线程,直到队列中有元素;当队列满时,put()方法会阻塞线程,直到队列中有空闲位置。
以下是一个简单的示例代码:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerExample {
private static final int QUEUE_CAPACITY = 10;
private static final int NUM_PRODUCERS = 2;
private static final int NUM_CONSUMERS = 3;
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY);
for (int i = 0; i < NUM_PRODUCERS; i++) {
new Thread(new Producer(queue)).start();
}
for (int i = 0; i < NUM_CONSUMERS; i++) {
new Thread(new Consumer(queue)).start();
}
}
static class Producer implements Runnable {
private final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
queue.put(i);
System.out.println("Produced: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Consumer implements Runnable {
private final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
Integer value = queue.take();
System.out.println("Consumed: " + value);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}