Java – how to kill a running thread while waiting?

When I try to kill my bandit thread, some people die, but some people fall into wait() blocking. What is a better way to kill all threads, or how can I kill the blocked threads?

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;
}

Solution

The correct way to "kill" a thread is to use thread Interrupt() interrupts it If the thread is blocked in a wait (...) call, an interruptedexception is thrown immediately When you catch an interruptedexception, it's best to interrupt the thread immediately to keep the interrupt flag, because the interrupt bit is cleared when an exception is thrown

try {
    ...wait();
} catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
    // handle the interrupt
    return;
}

Since not all methods throw interruptedexception, you can also check to ensure that the thread has been interrupted, as follows:

if (Thread.currentThread().isInterrupted()) {
    // stop processing
    return;
}

Or in your case, for example:

while (alive && !Thread.currentThread().isInterrupted()) {

By the way, live should be volatile because it seems to be accessed by multiple threads

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>