思路:我们需要一个生产商品的线程类,以及一个消费商品的线程类,还有一个工具类,是编写生产以及消费的方法,供线程去调用
工具类:
/**
* 工具类,生产与消费的方法
*/
class Cherk{
// 商品库存
private int product = 0;
// 10个商品为最大库存量,为此生产出一个商品
public synchronized void product() {
while (product==10){
System.out.println("库存已满");
try {
// 当库存满的时候,线程调用wait方法,会释放锁
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
product++;
System.out.println(Thread.currentThread().getName()+"生产了一个商品,当前库存为:"+product);
System.out.println("仓库有货,数量为:"+product);
// 唤醒其他等待的线程
this.notifyAll();
}
// 消费方法,每次消费商品数量减一
public synchronized void consumer() {
while (product<=0){
System.out.println("没货了,心里没点数吗?");
try {
// 当缺货了,就不让消费了,等待生产者生产商品
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
product--;
System.out.println(Thread.currentThread().getName()+"消费了一个商品");
// 唤醒等待的线程
this.notifyAll();
}
}
生产者:
class JymProducer implements Runnable{
// 有一个Cherk类,供线程调用方法
private Cherk cherk;
public JymProducer(Cherk cherk) {
this.cherk = cherk;
}
// 默认生产20次
public void run() {
for(int i = 0; i<20; i++){
cherk.product();
}
}
}
消费者:
class JymConsumer implements Runnable{
// 有一个Cherk类,供线程调用方法
private Cherk cherk;
public JymConsumer(Cherk cherk) {
this.cherk = cherk;
}
// 默认生产20次
public void run() {
for(int i = 0; i<20; i++){
cherk.consumer();
}
}
}
测试代码:
public class ProductAndConsumer {
public static void main(String[] args) {
Cherk cherk = new Cherk();
new Thread(new JymProducer(cherk),"生产者A").start();
new Thread(new JymProducer(cherk),"生产者B").start();
new Thread(new JymConsumer(cherk),"消费者A").start();
new Thread(new JymConsumer(cherk),"消费者B").start();
}
}