多线程中能量守恒那个例子,思想是按照视频的,代码自己重编的,但是每次运
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=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] |
免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。
版权声明:作者保留权利,不代表天盟立场。
|
|
|
|
第十行代码: privateObjectlock=newObject(); 将此段代码改为private static Objectlock=newObject();
synchronized(lock) 要保证lock是同一个对象 |
|
|
|
|