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