public class ProducerAndConsumer {
private final int max = 10;
private Queue<Integer> queue = new LinkedList<>();
class Product extends Thread {
@Override
public void run() {
producter();
}
private void producter() {
while (true) {
synchronized (queue) {
while (queue.size() == max) {
queue.notify();
//通知同一个对象上已执行wait()方法且获得对象锁的等待线程
System.out.println("当前队列已满");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(1);
queue.notify();
System.out.println("生产者生产一条任务,当前队列长度为" + queue.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Coustmer extends Thread {
@Override
public void run() {
coustmer();
}
private void coustmer() {
while (true) {
synchronized (queue) {
while (queue.size() == 0) {
queue.notify();
System.out.println("当前队列为空");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
queue.notify();
System.out.println("消费者消费一条任务,当前队列长度为" + queue.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
ProducerAndConsumer p = new ProducerAndConsumer();
Product product = p.new Product();
Coustmer coustmer = p.new Coustmer();
product.start();
coustmer.start();
}
}
生产者消费者模式
最新推荐文章于 2024-04-18 10:40:14 发布