public class TestThreads{
private static Object resource = new Object();
private static void delay(long n){
try{
Thread.sleep(n);
}catch(Exception e){
System.out.print(Thread.currentThread().getName() + "Error ");
}
}
public static void main(String[] args){
System.out.print("StartMain ");
new Thread1().start();
delay(1000);
Thread t2 = new Thread2();
t2.start();
delay(1000);
t2.interrupt();
delay(1000);
System.out.print("EndMain ");
}
static class Thread1 extends Thread{
public void run(){
synchronized(resource){
System.out.print("Start1 ");
delay(6000);
System.out.print("End1 ");
}
}
}
static class Thread2 extends Thread{
public void run(){
synchronized(resource){
System.out.print("Start2 ");
delay(2000);
System.out.print("End2 ");
}
}
}
}打印的结果是:StartMain Start1 EndMain End1 Start2 Error End2
问题是,Error为什么会打印出来?应该是由main方法中调用了t2.interrupt()语句导致Thread2线程捕获到一个InterruptedException,从而打印出Error,但是从结果中可以看出,EndMain在Start2之前打印,说明Main方法在线程Thread2执行前就已经结束了,怎么t2.interrupt()语句还好产生作用呢?问题长了点,但应该不复杂,请大家耐心看下,谢谢指点

解决方案 »

  1.   

    main虽然结束了,但Java虚拟机并没结束
      

  2.   

    Thread t2 = new Thread2();
    t2.start();
    线程2已经启动,不过在等待同步锁,
    主线程调用 interrupt就置了一个中断标志,以后线程2调用sleep方法就会抛出异常,不需要在
    sleep的时候中断才抛出异常。
      

  3.   

    刚查了下源码中的注释,interrupt方法注释最后一句是,If none of the previous conditions hold then this thread's interrupt status will be set.
    应该就是楼上说的这个意思吧