Java – 中断线程?
我有一个关于在Java中断线程的问题。 说我有一个Runnable
:
public MyRunnable implements Runnable { public void run() { operationOne(); operationTwo(); operationThree(); } }
我想实现这样的事情:
Thread t = new Thread(new MyRunnable()); t.run(); ... // something happens // we now want to stop Thread t t.interrupt(); // MyRunnable receives an InterruptedException, right? ... // t is has now been terminated.
我怎样才能在Java中实现它? 具体来说,我如何捕获MyRunnable
的InterruptedException
?
我建议测试Thread.isInterrupted()
。 Javadoc 在这里 。 这里的想法是你正在做一些工作,很可能是在循环中。 在每次迭代时,您应检查中断标志是否为真并停止工作。
while(doingWork && !Thread.isInterrupted() { // do the work }
编辑 :要清楚,如果子任务没有阻塞或最坏,您的线程将不会收到InterruptedException
,吃掉该exception。 检查标志是正确的方法,但不是每个人都遵循它。
首先,第二个代码块的第二行应该是t.start(),而不是t.run()。 t.run()只是在线调用你的run方法。
是的,MyRunnable.run()在Thread.currentThread()。isInterrupted()时必须定期检查它是否正在运行。 由于你可能想要在Runnable中做的很多事情涉及InterruptedExceptions,我的建议是咬紧牙关并与他们一起生活。 定期调用实用程序function
public static void checkForInterrupt() throws InterruptedException { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); }
编辑补充说
由于我看到海报无法控制各个操作的评论,他的MyRunnable.run()代码应该看起来像
public void run() { operation1(); checkForInterrupt(); operation2(); checkForInterrupt(); operation3(); }
只有在线程被阻塞(等待,hibernate等)时才会抛出InterruptedThreadException
。 否则,您将必须检查Thread.currentThread().isInterrupted()
。
我认为上面的答案非常适合你的问题。 我只是想在InterruptedException
上添加一些内容
Javadoc说:
InterruptedException:当线程等待,hibernate或以其他方式暂停很长一段时间时抛出,另一个线程使用Thread类中的interrupt方法中断它。
这意味着运行时不会抛出InterruptedException
operationOne(); operationTwo(); operationThree();
除非你正在睡觉,等待锁定或在这三种方法中暂停某个地方。
编辑如果提供的代码无法按照这里的好用和有用的答案的建议进行更改,那么我担心您无法中断您的线程。 与C#等其他语言相似,可以通过调用Thread.Abort()
来中止线程.Java没有这种可能性。 请参阅此链接以了解有关确切原因的更多信息。
首先,应该在那里上课
public class MyRunnable extends Thread { public void run() { if(!isInterrupted()){ operationOne(); operationTwo(); operationThree(); } } }
这会更好吗?