能量守恒中是否会出死锁的问题?
我按照视频中的代码重写了一编,发现在运行时经常会不出数据,但是程序还没子啊运行,是不是死锁
我按照视频中的代码重写了一编,发现在运行时经常会不出数据,但是程序还没子啊运行,是不是死锁
2016-07-29
这个设置了,这是我的代码,我跟视频上不完全一样,一个是测试,一个thread,谢谢了
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(); } } }
举报