java 生产者消费者问题-多线程与死锁

来源:互联网 发布:淘宝降价通知 编辑:程序博客网 时间:2024/05/29 18:37


代码直接示例。


//想象这是馒头,每个馒头有自己的id

class Item{

private int id=0;
public Item(int id) {
this.id=id;
}
public int getID(){
return id+1;
}
}

//想象这是装馒头的框子

class Stack{

//最多装5个的数组

Item []arr=new Item[5];

int index=0;  //记录装了几个

//添加与移除方法:都得上锁,不然乱了。关于这个问题点击打开链接,这里有一个例子找看看

public synchronized void add(Item it){
while(index==5){
try {
wait();   //如果满了就不能装了,线程wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}

arr[index]=it;
index++;

notify();    //别忘了唤醒移除线程


public synchronized Item remove(){
while(index==0){
try {
this.wait();    没了就不能去除了,wait
} catch (InterruptedException e) {
e.printStackTrace();
}

}


notify();   //唤醒添加线程。刚才不是wait了吗,然后进行一些操作:
index--;
Item it=arr[index];
arr[index]=null;


return it;

}
}

生产馒头的:生产者
class Produce implements Runnable{
  Stack s=null;
public Produce(Stack s){
this.s=s;

}

//生产20个就算了吧,不然循环起来没完了

public void run(){
for(int i=0;i<20;i++){
s.add(new Item(i));
System.out.println("Pro: "+(i+1));
try {
Thread.sleep(400);  睡一会是为了更好的观察输出,你设成0的话 再看就看不出来运行过程了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}


消费者

class Consume implements Runnable{
Stack s=null;
public Consume(Stack s){
this.s=s;
}
public void run(){
for(int i=0;i<20;i++){
System.out.println("Remove: "+ s.remove().getID());
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}


public class TestPandC{
public static void main(String[] args){
Stack s=new Stack();
new Thread(new Produce(s)).start();
new Thread(new Consume(s)).start();
}

}

运行一下看看吧




0 0