java单线程。interrupt()中断多次
我创建了MyTask
,它在run()
内有3件事要做。我尝试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)
,它开始正常工作,并在控制台上打印First task
、Second task
和最后Third task
问题是:为什么只有当我添加sleep()
时Thread.interrupts()
才能正常工作
public class MyTask implements Runnable {
private volatile Thread thread;
@Override
public void run() {
while (!thread.isInterrupted()) {
System.out.println("First task");
}
try {
Thread.sleep(10);
} catch (Exception e) {
}
while (!thread.isInterrupted()) {
System.out.println("Second task");
}
try {
Thread.sleep(10);
} catch (Exception e) {
}
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();
}
}
# 1 楼答案
请看一下
Thread.sleep(long)
上的Javadoc因此,添加
sleep
以及捕获(并输入)任何异常将导致观察到的行为例如:
没有
sleep()
:interrupted = false
开始,因此第一个循环运行interrupted = true
interrupted
并且没有运行(再次)interrupted
并且根本不运行interrupted
并且根本不运行用
sleep()
interrupted = false
开头循环1:
interrupted = false
起检查条件并执行正文时interrupted = true
interrupted = true
因此循环结束interrupted = false
对循环2和3重复步骤2
# 2 楼答案
引自Interrupts:
意思:将代码从
thread.isInterrupted()
更改为Thread.interrupted()
,然后重试循环之间的
sleep()
也将通过立即抛出InterruptedException
清除该标志(因为当前线程已被中断)