Java生产者消费者模式是一种多线程同步机制,它用于在一个线程中生产物品,另一个线程消费这些物品。它通常用于实现缓冲区,以确保生产者不会因为缓冲区满而无法生产新的物品,同时也确保消费者不会因为缓冲区空而无法消费物品。
Java生产者消费者模式是一种多线程同步机制,它用于在一个线程中生产物品,另一个线程消费这些物品。它通常用于实现缓冲区,以确保生产者不会因为缓冲区满而无法生产新的物品,同时也确保消费者不会因为缓冲区空而无法消费物品。
是一个使用java实现生产者消费者模式的示例代码:
public class ProducerConsumerExample {
public static void main(String[] args) {
Buffer buffer = new Buffer(10);
Thread producerThread = new Thread(new Producer(buffer));
Thread consumerThread = new Thread(new Consumer(buffer));
producerThread.start();
consumerThread.start();
}
}
class Buffer {
private int capacity;
private Queue
public Buffer(int capacity) {
this.capacity = capacity;
}
public synchronized void put(int value) throws InterruptedException {
while (queue.size() == capacity) {
wait();
}
queue.add(value);
notifyAll();
}
public synchronized int get() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
int value = queue.remove();
notifyAll();
return value;
}
}
class Producer implements Runnable {
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
int i = 0;
while (true) {
System.out.println("Producer is producing item " + i);
buffer.put(i++);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
while (true) {
System.out.println("Consumer is consuming item " + buffer.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(71条)