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

标签 java multithreading wait

当我试图杀死我的 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/

相关文章:

c# - 产生工作线程

c++ - 创建新线程时复制构造函数调用

c# - 如何异步等待 x 秒然后执行某些操作?

java - 安卓穿戴: very strange wait cycle

c - 在MPI中,如何编写下面的程序 等待所有计算完成

java - spring Kafka ConsumerFactory bean 未找到

java - Google Guice - 使用泛型作为注入(inject)字段的参数

java - Android 在特定时间后启动/停止重复线程

java - 如何修复 Java 代码 Catch block 中的以下错误?

java - java中访问对象变量