package?project_thread;
public?class?EnergyThread?extends?Thread?{
private?final?double[]?energy_box;
private?double?energy_max;
private?Object?lock=new?Object();
?????@Override
????public?void?run()?{
???? //?TODO?Auto-generated?method?stub
????
???? ?while?(true)?{
int?from=(int)?(Math.random()*getlength());
int?to?=(int)?(Math.random()*getlength());
double?energy=Math.random()*energy_max;
int?time=(int)?(Math.random()*50);
energy_tansform(from,?to,?energy);
try?{
sleep(time);
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
????}
?????public?EnergyThread(double?energy_initial,int??n)?{
//?TODO?Auto-generated?constructor?stub
???? ?this.energy_box=new?double[n];
???? ?this.energy_max=energy_initial;
???? ?for?(int?i?=?0;?i?<?n;?i++)?{
energy_box[i]=energy_initial;
}
}
?????
?????public?int?getenergy_total()?{
???? ?double?total=0;
???? ?for?(double?d?:?energy_box)?{
total+=d;
}
return?(int)total;
}
?????
?????public?void?energy_tansform(int?from,int?to?,double?energy)?{
synchronized?(lock)?{
if(energy_box[from]<energy){
try?{
lock.wait();
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
energy_box[from]-=energy;
energy_box[to]+=energy;
System.out.println(getName()+":energy_box["+from+"]向energy_box["+to+"]轉(zhuǎn)移"+energy+"energy_total="+getenergy_total());
lock.notifyAll();
}
}
?????
?????public?int??getlength()?{
return?energy_box.length;
}
}//這是另一個測試
package?project_thread;
public?class?ThreadTest?{
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
????????
?????????for(int?i=0;i<100;i++){
???????? ?Thread?thread=new?EnergyThread(1000,100);
???????? ?thread.start();
?????????}
????????
}
}這是為什么呢,求大神解答
1 回答
已采納

Lookiy
TA貢獻4條經(jīng)驗 獲得超3個贊
?第十行代碼: private?Object?lock=new?Object(); 將此段代碼改為?private static? Object?lock=new?Object();
?synchronized(lock) 要保證lock是同一個對象
添加回答
舉報
0/150
提交
取消