*24. What will be the output on compiling/running the following code? 
public class MyThread implements Runnable { 
String myString = "Yes "; 
public void run() { 
this.myString = "No "; 

public static void main(String[] args) { 
MyThread t = new MyThread(); 
new Thread(t).start(); 
for (int i=0; i < 10; i++) 
System.out.print(t.myString); 

} A. compile error 
B. prints: yes yes yes yes yes yes and so on 
C. prints: no no no no no no no no and so on 
D. prints: yes no yes no ye no ye no and so on 
E. the output cannot be determinated Answer B

解决方案 »

  1.   

    SCJP的考题比较变态
    貌似先执行了主线程,但是也不尽然,我这样:
    public class MyThread implements Runnable { 
    String myString = "Yes "; 
    public void run() { 
    this.myString = "No ";
    for (int i=0; i < 10; i++) 
    System.out.print(this.myString); 

    public static void main(String[] args) { 
    MyThread t = new MyThread(); 
    new Thread(t).start(); 
    for (int i=0; i < 10; i++) 
    System.out.print(t.myString); 


    结果就有一次打出了Yes Yes Yes No No No No No No No No No No No No No No No No No
    另一次打出了      Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No No No No No No No No No No
      

  2.   

    答案应该是E,你的答案有问题线程start以后不是马上运行,而是进入runnable状态,是否运行,以及运行哪个,何时运行就不是人为可以决定的了