二话不说 直接上题
import java.util.*;
public class TestInterrupt{
public static void main(String[]args){
Thread st= new MyThread();
st.start();
try{
Thread.sleep(10000);
}
catch(InterruptedException a){ }
st.interrupt();
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println("aaa");
try{
sleep(1000);//睡眠时间是一秒 interrupt是怎么中断他的?
}catch(InterruptedException d){
return;
}
}
}
}
import java.util.*;
public class TestInterrupt{
public static void main(String[]args){
Thread st= new MyThread();
st.start();
try{
Thread.sleep(10000);
}
catch(InterruptedException a){ }
st.interrupt();
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println("aaa");
try{
sleep(1000);//睡眠时间是一秒 interrupt是怎么中断他的?
}catch(InterruptedException d){
return;
}
}
}
}
}catch(InterruptedException d){
d.printStackTrace();然後你就會得到像這樣的錯誤訊息。
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at test2.MyThread.run(MyThread.java:19)他說明了在MyThread的 sleep(1000);的時候被TestInterrupt的 st.interrupt(); 中斷了。
当时interrupt当时醒,睡不足1秒的,呵呵。
这时主线程苏醒 开始执行 实行中断子线程操作
这是子线程应该是又执行一次输出操作 然后被中断才是
可为什么 结果是输出10次“aaa”然后捕捉住异常 执行return 子线程结束 而不是11次aaa
因为程序执行也需要花时间,而且主线程和先程谁先谁后执行由CPU控制,所以两者的睡眠时间不完全保证一致。当线程执行到第10次,打印aaa后,线程进入睡眠,此时主线程的睡眠可能已经过了10秒,这时主线程醒了,继续执行中断线程,而线程中断,走到异常返回,程序结束