模型描述:
java线程中典型的生产者与消费者模式,综合运用到thread中的notify()和wait();
仓库Godown的固定的容量大小max_size,同时有多个生产者向仓库生产放他产品,同时又有多个消费都从仓库取出产品,这就涉及到生产和消费过程中的同步问题,利用多线程技术可以很好的解决这个问题
1、生产者模型,定义为一个线程即实现Thread类
2、消费模型
仓库模型(核心代码)
测试代码
java线程中典型的生产者与消费者模式,综合运用到thread中的notify()和wait();
仓库Godown的固定的容量大小max_size,同时有多个生产者向仓库生产放他产品,同时又有多个消费都从仓库取出产品,这就涉及到生产和消费过程中的同步问题,利用多线程技术可以很好的解决这个问题
1、生产者模型,定义为一个线程即实现Thread类
package com.leiht.thread.waitnotify;
public class Producer extends Thread {
private int needNum;
private Godown godown;
public Producer(int needNum, Godown godown) {
this.needNum = needNum;
this.godown = godown;
}
@Override
public void run() {
godown.produce(needNum);
}
public int getNeedNum() {
return needNum;
}
public void setNeedNum(int needNum) {
this.needNum = needNum;
}
public Godown getGodown() {
return godown;
}
public void setGodown(Godown godown) {
this.godown = godown;
}
}
2、消费模型
package com.leiht.thread.waitnotify;
public class Consumer extends Thread {
private int needNum;
private Godown godown;
public Consumer(int needNum, Godown godown) {
this.needNum = needNum;
this.godown = godown;
}
@Override
public void run() {
godown.consume(needNum);
}
public int getNeedNum() {
return needNum;
}
public void setNeedNum(int needNum) {
this.needNum = needNum;
}
public Godown getGodown() {
return godown;
}
public void setGodown(Godown godown) {
this.godown = godown;
}
}
仓库模型(核心代码)
package com.leiht.thread.waitnotify;
public class Godown {
public int current_size;
public static final int max_size = 100;
public static int getMaxSize() {
return max_size;
}
public Godown(int current_size) {
this.current_size = current_size;
}
/*
* 生产方法
*/
public synchronized void produce(int needNum) {
//可以生产
if((needNum + current_size) < max_size) {
System.out.println("开始生产");
current_size = current_size + needNum;
System.out.println("生产完成");
notifyAll();
}else { //不能生产 将当前线程挂到this(当前)对象上
try {
System.out.println("当前库存过大,挂起等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*
* 消费方法
*/
public synchronized void consume(int needNum) {
if(needNum > current_size) {
try {
System.out.println("当前商品不足,等等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("开始消费");
current_size = current_size - needNum;
System.out.println("结束消费");
notifyAll();
}
}
测试代码
package com.leiht.thread.waitnotify;
public class Test {
public static void main(String[] args) {
Godown godown = new Godown(30);
Consumer c1 = new Consumer(50, godown);
Consumer c2 = new Consumer(20, godown);
Consumer c3 = new Consumer(30, godown);
Producer p1 = new Producer(10, godown);
Producer p2 = new Producer(10, godown);
Producer p3 = new Producer(10, godown);
Producer p4 = new Producer(10, godown);
Producer p5 = new Producer(10, godown);
Producer p6 = new Producer(10, godown);
Producer p7 = new Producer(80, godown);
c1.start();
c2.start();
c3.start();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
p7.start();
}
}