前言
生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,生产者往存储空间中添加产品,消费者从存储空间中取走产品,当存储空间为空时,消费者阻塞,当存储空间满时,生产者阻塞。
/**
* @description 生产者/消费者:生产者生产了产品,消费者才能消费产品
**/
public class Day63 {
/**
* product:1--有产品,0--没产品
*/
static int product = 0;
static String lock = new String();
public static void main(String[] args) {
Producer p = new Producer();
Consumer c = new Consumer();
p.start();
c.start();
}
}
class Producer extends Thread {
int count = 0;
@Override
public void run() {
while (true) {
try {
sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (Day63.lock) {
if (Day63.product == 1) {
System.out.println("已经有产品了,请生产者等待。");
try {
Day63.lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
} else if (Day63.product == 0) {
Day63.product++; //生产产品
count++;
System.out.println("生产者生产了第" + count + "个产品。");
System.out.println("通知消费者消费产品。");
try {
Day63.lock.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
class Consumer extends Thread {
int count = 0;
@Override
public void run() {
while (true) {
try {
sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (Day63.lock) {
if (Day63.product == 1) {
Day63.product--; //消费产品
count++;
System.out.println("消费了第" + count + "个产品");
System.out.println("通知生产者生产!");
try {
Day63.lock.notify();
} catch (Exception e) {
e.printStackTrace();
}
} else if (Day63.product == 0) {
System.out.println("没有产品,请消费者等待。");
try {
Day63.lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}