Object的wait和notify实现生产者和消费者
public class ConsumerAndProducer {
private int queueSize = 10;
private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);
public static void main(String[] args) {
ConsumerAndProducer consumerAndProducer = new ConsumerAndProducer();
Consumer consumer = consumerAndProducer.new Consumer();
Producer producer = consumerAndProducer.new Producer();
consumer.start();
producer.start();
}
class Consumer extends Thread {
@Override
public void run() {
comsume();
}
private void comsume() {
while (true) {
synchronized (queue) {
if (queue.size() == 0) {
try {
System.out.println("队列空,等待数据");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
queue.notify();
}
}
queue.poll();
queue.notify();
System.out.println("从队列取走一个元素,剩余" + queue.size() + "个元素");
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
produce();
}
private void produce() {
while (true) {
synchronized (queue) {
if (queue.size() == queueSize) {
try {
System.out.println("队列已满,等待空位");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
queue.notify();
}
}
queue.offer(1);
queue.notify();
System.out.println("向队列插入一个元素,剩余空间:" + (queueSize - queue.size()));
}
}
}
}
}