package com.javabase.obj.thread;
/** 仓库用于存放产品,调用生产方法和消费方法
* @author Administrator
*
*/
public class Depot {
private int number=5;//初始数量
public static final int MAX=10;
public static final int MIN=0;
//添加商品的方法,如果商品的个数满了,就行等待,否则进行生产,并唤醒消费者消费
public synchronized void addNumber() {
if(number>=MAX) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (number<MAX) {
this.number++;
System.out.println(Thread.currentThread().getName()+"生产了一个商品,库存量为:"+this.number);
//通知消费者进行消费
this.notifyAll();
}
}
//消费产品的方法,同步处理
public synchronized void subNumber() {
if(number<=MIN) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(number>MIN) {
this.number --;
System.out.println(Thread.currentThread().getName()+"消费了一个商品,库存量为:"+this.number);
//通知生产者开始生产 ,调用这个方法时候并会触发
this.notifyAll();
}
}
}
package com.javabase.obj.thread;
//创建生产者
public class Producter extends Thread{
private Depot d;
public Producter(String name,Depot d) {
super(name);//代表个新的线程
this.d=d;
}
public void run() {
while(true) {
try {
//隔一秒调用 一次生产
sleep(1000);
this.d.addNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.javabase.obj.thread;
//消费者方法
public class Customer extends Thread{
private Depot d;
public Customer(String name,Depot d) {
super(name);
this.d=d;
}
public void run() {
while(true) {
try {
sleep(1000);
this.d.subNumber();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.javabase.obj.thread;
public class TestRun {
public static void main(String[] args) {
Depot d=new Depot();
Producter p=new Producter("p1", d);
Producter p1=new Producter("p2", d);
Producter p2=new Producter("p3", d);
Customer c=new Customer("c1", d);
Customer c1=new Customer("c2", d);
Customer c2=new Customer("c3", d);
p.start();
p1.start();
p2.start();
c.start();
c1.start();
c2.start();
}
}