【发布时间】:2016-03-25 03:32:24
【问题描述】:
我创建了 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。
问题是:为什么Thread.interrupts() 只有在我添加sleep() 时才能正常工作?
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();
}
}
【问题讨论】:
标签: java multithreading interrupt