如何在等待中杀死正在运行的线程?

jav*_*vah 3 java multithreading wait

当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了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;
}
Run Code Online (Sandbox Code Playgroud)

Gra*_*ray 6

当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了wait()阻止,这将是一个更好的杀死所有线程的方法,

"杀死"一个线程的正确方法是用它来中断它thread.interrupt().如果线程在wait(...)通话中被阻止,则会立即抛出InterruptedException.当你发现 InterruptedException它时,最好立即重新中断线程以保留中断标志,因为当抛出异常时,中断位被清除.

try {
    ...wait();
} catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
    // handle the interrupt
    return;
}
Run Code Online (Sandbox Code Playgroud)

由于并非所有方法都抛出InterruptedException,您还可以检查以确保线程已被中断,如下所示:

if (Thread.currentThread().isInterrupted()) {
    // stop processing
    return;
}
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下,例如:

while (alive && !Thread.currentThread().isInterrupted()) {
Run Code Online (Sandbox Code Playgroud)

顺便说一句,alive应该是volatile因为它看起来被多个线程访问.