java生产者消费者模型

/**

  • 生成者,消费者,产品,容器
  • @author Administrator

*/
public class ProducerConsumer {
public static void main(String[] args) {
Container ct = new Container();//生成容器
//生产者消费者拥有同一个容器
Producer p = new Producer(ct);
Consumer c = new Consumer(ct);
Thread t1 = new Thread(p);//生产者线程
Thread t2 = new Thread(c);//消费者线程
//Thread t3 = new Thread(c);//消费者线程
//Thread t4 = new Thread(c);//消费者线程
t1.start();
t2.start();
}
}
//1.先定义产品类
class Product{
//产品id
int id ;
Product(int id){
this.id = id;
}
public String toString(){
return "product"+id;
}
}
//2.再定义容器类
class Container{
//定义容器的容量
Product [] p = new Product[5];
//容器当前存放产品位置
int index =0;
//往容器里放东西
public synchronized void put(Product pro){
while(indexp.length){
try {
//生产满了要等待消费
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//唤醒生产者
this.notify();
p[index] = pro;
System.out.println("生产了"+pro);
index++;
}
//从容器中拿走产品
public synchronized Product get(){
//因为index位置没有产品,所以要先--
while(index
0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
Product p2 = p[index];
System.out.println("消费了"+p2);
return p2;
}
}
//定义生产者实现了Runnable接口
class Producer implements Runnable{
Container c = null;
Producer(Container c){
this.c = c;
}
@Override
public void run() {
//生产了30个产品
for(int x = 1;x<=30;x++){
Product p = new Product(x);
//往里面放产品
c.put(p);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}
//4.定义消费者从里面拿东西也实现Runnable接口
class Consumer implements Runnable{
Container c = null;
Consumer(Container c){
this.c = c;
}
@Override
public void run() {
for(int x = 1;x<=30;x++){
//从里面拿产品
c.get();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

	}

}

}

posted @ 2019-06-17 16:13  韦大仙  阅读(440)  评论(0编辑  收藏  举报