What will happen when you attempt to compile and run the following code? public class MyThread extends Thread{ 
  String myName; 
  MyThread(String name) { 
   myName = name; 
  } 
  public void run(){ 
    for(int i=0; i<100;i++){ 
      System.out.println(myName); 
    } 
  } 
  public static void main(String args[]) { 
    try{ 
       MyThread mt1 = new MyThread("mt1"); 
       MyThread mt2 = new MyThread("mt2"); 
       mt1.start(); 
       // XXX 
       mt2.start(); 
    }
    catch(InterruptedException ex){ } 
  } 
}
 
A. compile error 
B. mt1.join(); 
C. mt1.sleep(100); 
D. mt1.run() 
E. nothing need 
请给出答案,并解释一下原因

解决方案 »

  1.   

    B,
    如果不加,不会抛出异常。(当然什么都不加就会compile error,不清楚为什么会有这个选项)
    mt1.join(),是指mt2要等mt1执行结束后才继续执行。
      

  2.   

    楼主回答正确,什么都不加会compile error
    为什么mt2要等mt1结束后才能继续执行呢?
      

  3.   

    线程本来就是并发运行了,编译错误是因为加了try{}catch(){}。
    现在try块里没有方法会抛InterruptedException异常,所以编译错误。
    把try{}catch(){}去掉就好了。
      

  4.   

    楼主回答正确,什么都不加会compile error
    为什么mt2要等mt1结束后才能继续执行呢?看一下关于join的使用。