直接上代码
public class InterruptDemo
{
public static void main(String[] args)
{ Thread thread1 = new Thread(new Runnable()
{
public void run()
{ try
{
Thread.sleep(1000);
System.out.println("I'm back");
}
catch (InterruptedException e)
{
System.out.println("I'm interrupted!!");
// e.printStackTrace();
}
}
});
thread1.start();
thread1.interrupt(); // 清除了所有的中断状态即
}
}
我的理解是如果执行了thread1.interrupt();应该打印 I'm interrupted!! 接着打印
I'm back,因为方法不是结束了阻塞吗,可现在的情况是只打印了I'm interrupted!!
在网上查了半天,觉得都说得含含糊糊,请大家指点一下,为什么不会打印出I'm back谢谢
public class InterruptDemo
{
public static void main(String[] args)
{ Thread thread1 = new Thread(new Runnable()
{
public void run()
{ try
{
Thread.sleep(1000);
System.out.println("I'm back");
}
catch (InterruptedException e)
{
System.out.println("I'm interrupted!!");
// e.printStackTrace();
}
}
});
thread1.start();
thread1.interrupt(); // 清除了所有的中断状态即
}
}
我的理解是如果执行了thread1.interrupt();应该打印 I'm interrupted!! 接着打印
I'm back,因为方法不是结束了阻塞吗,可现在的情况是只打印了I'm interrupted!!
在网上查了半天,觉得都说得含含糊糊,请大家指点一下,为什么不会打印出I'm back谢谢
中断线程。
如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。 如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。
所以你懂得若你把System.out.println("I'm back");放在Thread.sleep(1000)之前,就会执行System.out.println("I'm back");了
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("I'm not interrupted!");
} catch (InterruptedException e) {
System.out.println("I'm interrupted!");
}
System.out.println("I'm back!");
}
}); thread1.start();
int delay = 400;
//int delay = 1400;
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
thread1.interrupt();
}
}
如果 delay = 400,打印结果是I'm interrupted!
I'm back!因为 InterruptedException 发生在 Thread.sleep(1000) 处,后面的 System.out.println("I'm not interrupted!") 被跳过,执行直接进入 catch 的部分。
如果 delay = 1400,打印结果是I'm not interrupted!
I'm back!因为在 Thread.sleep(1000)中,InterruptedException 没有发生。