java线程已阻止 等待中_java – 如何在等待中杀死正在运行的线程?

当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值