java代码:
public class test {
public static void main(String[] args) throws InterruptedException {
Customer customer = new Customer();
customer.start(); // start customer
Thread.sleep(5000);
customer.interrupt(); // interrupt
}
}
class Customer extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("test Interrupted +++++");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我打电话给customer.interrupt(),但客户仍在工作;
控制台结果:
test Interrupted +++++
....
test Interrupted +++++
java.lang.InterruptedException: sleep interrupted
test Interrupted +++++
at java.lang.Thread.sleep(Native Method)
at com.yitai.common.redisQueue.Customer.run(test.java:22)
test Interrupted +++++
test Interrupted +++++
.... //more
如果我以这种方式更改代码: 在catch
中添加Thread.currentThread()。interrupt()try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // add this
e.printStackTrace();
}
客户停止了,但为什么? 控制台结果:
test Interrupted +++++
....
test Interrupted +++++
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.yitai.common.redisQueue.Customer.run(test.java:22)
// the end
答案 0 :(得分:0)
如果线程当前正在等待,调用Thread.interrupt()
清除线程的中断状态会导致循环继续。来自Javadoc(我的重点):
如果在调用Object类的
wait()
,wait(long)
或wait(long, int)
方法或join()
,join(long)
时阻止此线程},join(long, int)
,sleep(long)
或sleep(long, int)
,此类的方法,然后其中断状态将为 已清除 ,它将会收到InterruptedException
。
换句话说,如果线程当前有可能接收到InterruptedException
(因为它处于等待状态),那么将发送异常并清除中断状态。只有在无法同步传递异常时才会设置中断状态。
您需要在程序的逻辑中考虑到终止线程,假设这是您的意图。你需要正确处理两种可能性。