您的位置:首页 > 编程语言 > Java开发

interrupt()理解

2014-04-12 14:27 134 查看
之前对interrupt()方法一直不太理解,可能是这个名字太具有迷惑性了吧。
interrupt不能中断正在运行的线程,如下代码

class Example1 extends Thread {
boolean stop = false;
public static void main(String args[]) throws Exception {
Example1 thread = new Example1();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Interrupting thread...");
thread.interrupt();
System.out.println("thread interrupt()" + thread.isInterrupted());
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit(0);
}
public void run() {
while (!stop) {
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000)) {
}
}
System.out.println("Thread exiting under request...");
}
}
但是上面的代码还是有漏洞的,Example1对thread执行了interrupt操作,没有中断thread是因为interrupt方法只是在目标线程中设置了一个标志,表示它已经被中断。Example1对thread设置了中断标志但并没有检查这个标志是否被设置,所以Example1无法中断thread。对上面代码修改如下
class Example1 extends Thread {
boolean stop = false;
public static void main(String args[]) throws Exception {
Example1 thread = new Example1();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Interrupting thread...");
thread.interrupt();
System.out.println("thread interrupt()" + thread.isInterrupted());
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit(0);
}
public void run() {
//检查中断标志
while (!stop && !Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000)) {
}
}
System.out.println("Thread exiting under request...");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  interrupt java