当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了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;
}
解决方法:
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,multithreading,wait
来源: https://codeday.me/bug/20190728/1565252.html