线程通信问题
骑着蜗牛学 2013-12-30 02:15:05 package 生产者与消费者2;
public class Storg {
private int count;
private int size;
Storg(int size){
this.size=size;
}
//添加数据
public synchronized void addData(String n){
if(count==size){
try{
this.wait();
}catch(InterruptedException e){}
}else{
count++;
System.out.println(n+" make data count: "+count);
this.notify();
}
}
//删除数据
public synchronized void delData(String n){
if(count==0){
try{
this.wait();
}catch(InterruptedException e){}
}else{
System.out.println(n+" use data count: "+ count);
count--;
this.notify();
}
}
}
线程通信,这里是增减的方法,上面红色部分count应该是从1开始的,但是我运行总是5开始,会的大神求速度告诉我呀。
运行结果
Producer2 make data count: 5
Customer use data count: 5
Producer2 make data count: 5
Customer use data count: 5
Producer2 make data count: 5
Customer use data count: 5
Producer2 make data count: 5
Customer use data count: 5
Producer2 make data count: 5
Customer use data count: 5