有一道线程问题想不通,望大家指点下
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()语句还好产生作用呢?
问题长了点,但应该不复杂,请大家耐心看下,谢谢指点