Java 单线程.interrupt()中断多次
我创建了Java 单线程.interrupt()中断多次,java,multithreading,interrupt,Java,Multithreading,Interrupt,我创建了MyTask,它在run()中有三件事要做。我尝试interrupt()保存MyTask实例的线程。不幸的是,一旦中断,它就会结束,控制台上只打印字符串First task public class MyTask implements Runnable { private volatile Thread thread; @Override public void run() { while (!thread.isInterrupted()) {
MyTask
,它在run()中有三件事要做。我尝试interrupt()
保存MyTask
实例的线程。不幸的是,一旦中断,它就会结束,控制台上只打印字符串First task
public class MyTask implements Runnable {
private volatile Thread thread;
@Override
public void run() {
while (!thread.isInterrupted()) {
System.out.println("First task");
}
while (!thread.isInterrupted()) {
System.out.println("Second task");
}
while (!thread.isInterrupted()) {
System.out.println("Third task");
}
}
public Thread start(){
thread = new Thread(this);
thread.start();
return thread;
}
public static void main(String[] args) throws InterruptedException {
Thread t = new MyTask().start();
Thread.sleep(1000);
t.interrupt();
Thread.sleep(1000);
t.interrupt();
Thread.sleep(1000);
t.interrupt();
}
}
如果我在run()
中添加Thread.sleep(10)
,它将开始正常工作,并在控制台上打印第一个任务
,第二个任务
,最后打印第三个任务
public class MyTask implements Runnable {
private volatile Thread thread;
@Override
public void run() {
while (!thread.isInterrupted()) {
System.out.println("First task");
}
while (!thread.isInterrupted()) {
System.out.println("Second task");
}
while (!thread.isInterrupted()) {
System.out.println("Third task");
}
}
public Thread start(){
thread = new Thread(this);
thread.start();
return thread;
}
public static void main(String[] args) throws InterruptedException {
Thread t = new MyTask().start();
Thread.sleep(1000);
t.interrupt();
Thread.sleep(1000);
t.interrupt();
Thread.sleep(1000);
t.interrupt();
}
}
问题是:为什么只有在添加sleep()
时线程中断()才能正常工作
查看Thread.sleep(long)
抛出:InterruptedException-如果任何线程中断了当前线程。引发此异常时,当前线程的中断状态将被清除
因此,添加sleep
以及捕获(并输入)任何异常将导致观察到的行为
例如:
没有sleep()
:
- 线程以
interrupted=false开始,因此第一个循环运行
- 线程被中断,即现在
interrupted=true
- 第1个循环检查
中断
且不运行(再次)
- 第二个循环检查
中断
,根本不运行
- 第三个循环检查
中断
,根本不运行
- 完成
使用sleep()
线程以interrupted=false开始
循环1:
- 检查条件并执行正文时,因为
interrupted=false
- 线程被中断,即现在
interrupted=true
- 虽然条件已检查,但这次
中断=真
因此循环结束
- 调用
sleep()
,由于线程已中断,因此会引发异常,并再次interrupted=false
- 捕获(并忽略)异常,因此正常继续执行
对循环2和3重复步骤2
完成
引自:
当线程通过调用静态方法thread.interrupted检查中断时,中断状态被清除。一个线程用来查询另一个线程的中断状态的非静态isInterrupted方法不会更改中断状态标志
意思:将您的代码从thread.isInterrupted()
更改为thread.interrupted()
,然后重试
循环之间的sleep()
也将通过立即抛出InterruptedException
清除该标志(因为当前线程已被中断)您想说Thread.isInterrupted()到Thread.interrupted()吗