一直wait导致程序无法停止怎么解决?
试图停止线程,在EnergyTransferTask类中加入退出旗标,修改后代码如下:
public class EnergyTransferTask implements Runnable { private EnergySystem energySystem;// 共享的能量世界 private int fromBox;// 能量转移的源能量盒子下标 private double maxAmount;// 单次能量转移最大单元 private int DELAY = 10;// 最大休眠时间(毫秒) volatile boolean keepRunning = true; private int count = 0; public EnergyTransferTask(EnergySystem energySystem, int from, double max) { this.energySystem = energySystem; this.fromBox = from; this.maxAmount = max; } public void run() { try { while (keepRunning) { int toBox = (int) (energySystem.getBoxAmount() * Math.random()); double amount = maxAmount * Math.random(); energySystem.transfer(fromBox, toBox, amount); Thread.sleep((int) (DELAY * Math.random())); count++; if(count == 5){ keepRunning = false; } } } catch (InterruptedException e) { e.printStackTrace(); } } }
为了便于研究,将盒子数量BOX_AMOUNT改为2,但发现控制台的输出停止后,程序仍无法正常退出。推测是在wait set中线程一直在等待中,而其他线程已经执行完毕无法将其唤醒,有什么好的解决方法吗?