java多线程体验2-生产者消费者

今天接着复习一下多线程应用,对生产者和消费者模式又有了新的体会:
引用一下视频老师的吃馒头例子,在面包店里,馒头师傅负责生产馒头,
师傅一边生产一边往篮子里面放,我们几个就坐在旁边负责吃。
首先,定义一下馒头:

public class WoTou {

int id;
WoTou(int id){
this.id=id;

}
public String toString(){
return "WoTou:"+id;

}

}

然后,我们定义一下这个篮子,由于需要考虑多线程的应用,所以锁操作还是有必要的:
public class SyncStack {

int index=0;
final static int wtLength=6;
WoTou[] arrWt=new WoTou[wtLength];

public synchronized WoTou pop(){ //synchronized 锁住
while(index==0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notifyAll();
index--;
return arrWt[index];

}

public synchronized void push(WoTou wt){
while(index==wtLength){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notifyAll();
arrWt[index]=wt;
index++;
}

}

其次就是面包师傅的定义了:
public class Producer implements Runnable {


private SyncStack syncStack;
public Producer(SyncStack st){
syncStack=st;
}

public void run() {
for(int i=0;i<10;i++){
WoTou wt=new WoTou(i);
syncStack.push(wt);
System.out.println("生产了:"+wt);
}

}

}

最后就是我们这些只知道吃的啦:
public class Customer implements Runnable {
private SyncStack syncStack;
public Customer(SyncStack st){
syncStack=st;
}

public void run() {
for(int i=0;i<10;i++){
WoTou wt=syncStack.pop();
System.out.println("消费了:"+wt);
}

}


}

呵呵,那么,最后要看面包店啦:
public class testProducerCustomer {

/**
* @param args
*/
public static void main(String[] args) {
SyncStack st=new SyncStack();

Producer p=new Producer(st);
Customer c=new Customer(st);
//可雇佣多个面包师傅,就可以多几个人一起吃啦
Thread a=new Thread(p);
Thread b=new Thread(c);
//面包店开始运作啦
a.start();
b.start();

}

}

好啦,简单的消费者和生产者模式就写完啦,恩,找时间再加上实际项目的应用例子整理一下。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值