首页 新闻 赞助 找找看

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

0
[已关闭问题] 解决于 2018-09-14 09:59

第一种:
线程类
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”会不一样?

*青锋*的主页 *青锋* | 初学一级 | 园豆:180
提问于:2018-09-07 09:56
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册