当我试图杀死我的 Robber 线程时,有些死了,但有些卡在 wait() block 中,什么是杀死所有线程的更好方法,或者我如何让被阻塞的线程被杀死?
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;
}
最佳答案
When i try to kill my Robber threads, some die , but some get stuck in the wait() block , what would be a better way to kill all the threads ,
“杀死”线程的正确方法是使用thread.interrupt()
中断它。如果线程在 wait(...)
调用中被阻塞,这将立即抛出 InterruptedException
。当您捕捉到 InterruptedException
时,最好立即重新中断线程以保留中断标志,因为当抛出异常时,中断位会被清除。
try {
...wait();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
// handle the interrupt
return;
}
由于并非所有方法都会抛出 InterruptedException
,您还可以检查以确保线程已被类似以下内容中断:
if (Thread.currentThread().isInterrupted()) {
// stop processing
return;
}
或者在你的情况下是这样的:
while (alive && !Thread.currentThread().isInterrupted()) {
顺便说一句,alive
应该是 volatile
因为它看起来可以被多个线程访问。
关于java - 如何杀死等待中的正在运行的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433356/