ITPub博客

首页 > 应用开发 > > java多线程中,sleep和interrupt方法结合停止线程时,两种情况?

java多线程中,sleep和interrupt方法结合停止线程时,两种情况?

作者:pengjs991111 时间:2019-09-16 09:08:37 0 删除 编辑

第一种:

线程类

public class MyThread extends Thread {

@Override

public void run() {

try {

System.out.println("在沉睡中被停止,进入try!"+this.isInterrupted());

System.out.println("run begin");

Thread.sleep(200000);

System.out.println("run end");

} catch (Exception e) {

System.out.println("在沉睡中被停止,进入catch!"+this.isInterrupted());

e.printStackTrace();

}

}

}

测试类

public class Test {

public static void main(String[] args) {

try {

MyThread mt = new MyThread();

mt.start();

Thread.sleep(100);

mt.interrupt();

} catch (Exception e) {

System.out.println("main catch");

e.printStackTrace();

}

System.out.println("end!!!");

}

}

console结果:

在沉睡中被停止,进入try!false

run begin

end!!!

在沉睡中被停止,进入catch!false

java.lang.InterruptedException: sleep interrupted

at java.lang.Thread.sleep(Native Method)

at com.qf.MyThread.run(MyThread.java:14)

===============================================================

第二种:线程类不变,测试类注释sleep方法

public class Test {

public static void main(String[] args) {

try {

MyThread mt = new MyThread();

mt.start();

//Thread.sleep(100);

mt.interrupt();

} catch (Exception e) {

System.out.println("main catch");

e.printStackTrace();

}

System.out.println("end!!!");

}

}

console结果:

java.lang.InterruptedException: sleep interrupted

at java.lang.Thread.sleep(Native Method)

at com.qf.MyThread.run(MyThread.java:14)

end!!!

在沉睡中被停止,进入try!true

run begin

在沉睡中被停止,进入catch!false

想问下:

为什么两次结果“在沉睡中被停止,进入try!false”和“在沉睡中被停止,进入try!true”会不一样?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/623/viewspace-3121932/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    221
  • 访问量
    778