之前认为线程执行interrupt()后,张志和就会终止,实际并非如此,只是执行中中断。
看如下程序:
public class Test{
private static boolean isInterrupt=true;
public static void main(String[] args) {
Thread t = new Test().new Thread1();
System.out.println("1:"+t.getName());
t.start();
System.out.println("2:"+t.getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stop();//如果没有此名,虽然会输出一部分数字,但线程不会停止,第二输以后会输出全部数字
t.interrupt();//如果没有此名,1.2.3.4.5.6会全部输出
//注意,stop()使线程终止是因为改变了isInterrupt=false;
}
class Thread1 extends Thread{
public void run(){
while(isInterrupt){
try {
System.out.println(1);
Thread.sleep(1000);
System.out.println(2);
Thread.sleep(1000);
System.out.println(3);
Thread.sleep(1000);
System.out.println(4);
Thread.sleep(1000);
System.out.println(5);
Thread.sleep(1000);
System.out.println(6);
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().isInterrupted());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void stop(){
isInterrupt = false;
}
}