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+"]转移"+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条经验 获得超3个赞
第十行代码: private Object lock=new Object(); 将此段代码改为 private static Object lock=new Object();
synchronized(lock) 要保证lock是同一个对象
添加回答
举报
0/150
提交
取消