*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
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
貌似先执行了主线程,但是也不尽然,我这样:
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