當我試圖殺死我的強盜線程時,有些死亡,但有些卡在wait()塊中,那麼將會有更好的方法殺死所有線程,或者我如何獲得被阻塞的線程被殺死?如何殺死正在運行的線程?
private int robberId;
private static int robberGlobalId=0;
private TreasureChest chest;
private boolean alive = true;
public Robber(TreasureChest chest) {
robberId = robberGlobalId;
robberGlobalId++;
this.chest = chest;
}
public void run() {
while (alive) {
try {
synchronized(chest){
robCoin();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Robber " +robberId +" just died");
}
public void robCoin() throws InterruptedException {
if (chest.getTreasureAmount() <= 0) {
chest.wait();
} else {
chest.removeCoin();
}
Thread.sleep(50);
}
public void killRobber() {
alive = false;
}
http://arashmd.blogspot.com/2013/06/java-threading.html#shuttr – 2013-10-17 17:49:25