public class ThreadTest {
public static void main(String[] args) {
try {
System.out.println("try");
Thread thread = new MyThread();
thread.start();
thread.interrupt();
} catch (Exception e) {
System.out.println("1exception");
} finally {
System.out.println("finally");
}
}
}
class MyThread extends Thread {
public void run() {
try {
System.out.println("run");
Thread.sleep(100000);
System.out.println("addition");
//throw new Exception();
} catch (Exception e) {
System.out.println("2exception ");
}
System.out.println("adfsad");
}
}
这段代码的输出:
try
finally
run
2exception
adfsad
1 interrupt只是设置一个中断状态标志,线程在执行过程中会不停检查这个中断状态标志
2 中断状态标志不意味着该线程就要被中断进入阻塞状态,该干嘛干嘛。程序一般用Thread.interrupted()和Thread.currentThread().isInterrupted()还判断下面程序的执行,不同的是前者会清空中断,后者不会
3 interrupt()设置中断标志后,不管之前线程处于sleep状态还是之后尝试让线程sleep,都会抛出InterruptedException,代码如下
class MyThread2 extends Thread{
public void run(){
try{
System.out.println("aa");
this.interrupt();
System.out.println("bb");
for(int i=0;i<100000;i++)
;
Thread.sleep(1000);
System.out.println("cc");
}catch(InterruptedException e){
System.out.println("exception");
}
}
}
输出为:
aa
bb
exception
另外,空循环,JVM应该做了优化,不然没可能跑这么快的吧。
interrupt不再强制线程该干嘛或者回收线程有的资源,替代了stop方法。stop不好的地方:
从JDK1.2开始,这两个方法都被弃用了.stop天生就不安全,而经验告诉我们呢suspend方法会经常导致死锁。
反对使用stop(),是因为它不安全。它会解除由线程获取的所有锁定,当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,假如一个线程正在执行:synchronized void { x = 3; y = 4;} 由于方法是同步的,多个线程访问时总能保证x,y被同时赋值,而如果一个线程正在执行到x = 3;时,被调用了 stop()方法,即使在同步块中,它也干脆地stop了,这样就产生了不完整的残废数据。而多线程编程中最最基础的条件要保证数据的完整性,所以请忘记线程的stop方法,以后我们再也不要说“停止线程”了。而且如果对象处于一种不连贯状态,那么其他线程能在那种状态下检查和修改它们。结果 很难检查出真正的问题所在。