我创建了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)
,它就会开始正常工作并在控制台上打印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();
}
}