java – 如何在等待中杀死正在运行的线程?
发布时间:2020-12-15 04:14:37 所属栏目:Java 来源:网络整理
导读:当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了wait()阻止,什么是杀死所有线程的更好方法,或者我如何让被阻止的线程被杀死? private int robberId;private static int robberGlobalId=0;private TreasureChest chest;private boolean alive = true;
当我试图杀死我的强盗线程时,有些人死了,但有些人陷入了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; } 解决方法
“杀死”线程的正确方法是使用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,因为它看起来是多个线程访问的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |