您的位置:首页 > 编程语言 > Java开发

Java生产者消费者模式

2013-10-25 21:53 459 查看
package ProductConsumer;

import org.ietf.jgss.Oid;

public class Test {
public static void main(String[] args){
Market mt=new Market();
Product product=new Product(mt);
Consumer consumer=new Consumer(mt);
new Thread(product).start();
new Thread(consumer).start();

}

}

class Product implements Runnable{
Market market=null;
public Product(Market mt){
this.market=mt;
}

@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 20; i++) {
WoTou wt=new WoTou(i);
market.push(wt);
System.out.println("生产了:"+wt);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class Consumer implements Runnable{
Market market=null;
public Consumer(Market mt){
this.market=mt;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 60; i++) {
/*WoTou wt=new WoTou(i);
market.push(wt);*/
WoTou wTou=market.pop();
System.out.println("消费了:"+wTou);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class Market {
WoTou[] wtArr=new WoTou[6];
int index=0;
public synchronized void push(WoTou wt){
wtArr[index]=wt;
index++;

while(index==wtArr.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
}
public synchronized WoTou pop(){

while (index==0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
index--;
return wtArr[index];
}
}

class WoTou{
int id;
public WoTou(int id){
this.id=id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "WOTUO:"+id;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java设计模式