1 package com.service.cone; 2 3 public class EnergySystem { 4 5 //总能量 6 private final double[] energyBoxs; 7 8 private final Object obj = new Object(); 9 10 //个数和每个能量块的能量值 11 public EnergySystem(int n,double initialEnergy ) { 12 energyBoxs = new double[n]; 13 for (int i = 0; i < energyBoxs.length; i++) { 14 energyBoxs[i] = initialEnergy; 15 } 16 } 17 18 //能量转移 19 public void transfer(int from,int to,double amount) { 20 21 synchronized (obj) { 22 23 // if(energyBoxs[from]<amount){ 24 // return; 25 // } 26 27 while(energyBoxs[from]<amount){ 28 try { 29 // 30 obj.wait(); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 System.out.print(Thread.currentThread().getName()); 37 energyBoxs[from]-=amount; 38 System.out.printf("从%d转移 %10.2f单位能量到 %d",from,amount,to); 39 energyBoxs[to]+=amount; 40 System.out.printf("能量总和:%10.2f%n",getTotalEnergies()); 41 // 42 obj.notifyAll(); 43 } 44 } 45 46 //返回总能量 47 public double getTotalEnergies() { 48 double sum = 0; 49 for (double amount :energyBoxs) { 50 sum+=amount; 51 } 52 return sum; 53 } 54 55 //返回长度 56 public int getBoxAmount() { 57 return energyBoxs.length; 58 } 59 60 }
1 package com.service.cone; 2 3 public class EnergySystemTest { 4 5 //能量块的个数 6 public static final int BOX_AMOUNT = 100; 7 //每个能量块的初始化能量值 8 public static final double INITIAL_ENERGY = 1000; 9 10 11 12 public static void main(String[] args) { 13 14 EnergySystem eng = new EnergySystem(BOX_AMOUNT,INITIAL_ENERGY); 15 16 for (int i = 0; i < BOX_AMOUNT; i++) { 17 18 EnergyTransferTask task = new EnergyTransferTask(eng, i, INITIAL_ENERGY); 19 20 Thread t = new Thread(task,"TransferThread_"+i); 21 t.start(); 22 23 } 24 25 } 26 27 }
1 package com.service.cone; 2 3 public class EnergyTransferTask implements Runnable { 4 5 private EnergySystem energySystem; 6 7 //下标 8 private int fromBox; 9 10 //每次转换的最大能量 11 private double maxAmount; 12 13 //休眠时间 14 private int Delay = 10; 15 16 17 public EnergyTransferTask(EnergySystem energySystem,int from,double max) { 18 19 this.energySystem = energySystem; 20 this.fromBox = from; 21 this.maxAmount = max; 22 } 23 24 25 @Override 26 public void run() { 27 28 try { 29 while(true){ 30 31 // static double random() 32 // 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。 33 34 int toBox = (int)(energySystem.getBoxAmount()*Math.random()); 35 36 double amount = maxAmount*Math.random(); 37 38 energySystem.transfer(fromBox, toBox, amount); 39 40 Thread.sleep((int)(Delay*Math.random())); 41 42 } 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 47 } 48 49 }