Java多线程中的生产者与消费者模式
创建Factory类(工厂类)
public class Factory {
private int num = 0;
private static final int NUM_MAX = 100;
public synchronized void product() throws InterruptedException {
String name = Thread.currentThread().getName();
if (num<NUM_MAX) {
num++;
System.out.println(name+"生产了一个商品,还剩下"+num+"个商品");
}else {
System.out.println("仓库已满"+name+"无需生产");
this.wait();
this.notify();
}
}
public synchronized void sell() throws InterruptedException {
String name = Thread.currentThread().getName();
if (num>0) {
num--;
System.out.println(name+"销售了一个商品,还剩下"+num+"个商品");
}else {
System.out.println("仓库已空"+name+"无需销售");
this.notify();
this.wait();
}
}
}
创建 ProductRunnable 类(生产者类)
public class ProductRunnable implements Runnable{
private Factory factory;
public ProductRunnable(Factory factory) {
super();
this.factory = factory;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
factory.product();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
创建 SellRunnable类(销售者类)
public class SellRunnable implements Runnable{
private Factory factory;
public SellRunnable(Factory factory) {
super();
this.factory = factory;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
factory.sell();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
public class Main {
public static void main(String[] args) {
Factory factory = new Factory();
SellRunnable sellRunnable = new SellRunnable(factory);
ProductRunnable productRunnable = new ProductRunnable(factory);
Thread t0 = new Thread(sellRunnable,"小飞");
Thread t1 = new Thread(sellRunnable,"小焦");
Thread t2 = new Thread(sellRunnable,"小王");
Thread t3 = new Thread(sellRunnable,"小李");
Thread t4 = new Thread(productRunnable,"牛工");
Thread t5 = new Thread(productRunnable,"张工");
Thread t6 = new Thread(productRunnable,"龙哥 ");
Thread t7 = new Thread(productRunnable,"小牛");
t0.start();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
}
编写思路
作用:描绘工厂的生产与销售
分析:
对象:
工厂
剩余商品数量
最大可容纳商品数量
生产的方法
销售的方法
生产人员
死循环
生产
销售人员
死循环
销售
类:
工厂类
属性:
剩余商品数量
最大可容纳商品数量
方法:
生产的方法,一个线程安全的方法
步骤:
1,判断剩余商品数量小于最大可容纳商品数量
剩余商品数量++
提示:谁谁谁生产了一个产品,现在还有xxx个商品
唤醒消费线程
2,剩余商品数量大于等于最大可容纳商品数量
唤醒消费线程
提示:仓库已满,生产人员xxx休息
休眠当前线程
销售的方法,一个线程安全的方法
步骤:
1,判断剩余商品数量大于0
剩余商品数量--
提示:谁谁谁卖出一个产品,现在还有xxx个商品
唤醒生产者线程
2,剩余商品数量小于等于0
唤醒生产者线程
提示:已经无货,销售人员xxx休息
休眠当前线程
生产任务类
死循环调用生产方法
注意:生产任务与销售任务对象的所有的工厂对象为一个对象
销售任务类
死循环调用销售方法
注意:生产任务与销售任务对象的所有的工厂对象为一个对象
环境类
先写main方法
步骤:
1,创建工厂
2,创建生产任务,传入工厂
3,创建销售任务,传入工厂
4,创建生产人员
创建生产人员对象(线程对象),传入生产任务对象
创建生产人员对象(线程对象),传入生产任务对象
创建生产人员对象(线程对象),传入生产任务对象
创建生产人员对象(线程对象),传入生产任务对象
创建生产人员对象(线程对象),传入生产任务对象
...
5,创建销售人员
创建销售人员对象(线程对象),传入销售任务对象
...
6,启动线程