日期:2014-05-20  浏览次数:20758 次

又是多线程的输出问题- -
Question 126

1. import java.util.*;
2.
3. public class NameList {
4. private List names = new ArrayList();
5. public synchronized void add(String name) { names.add(name); }
6. public synchronized void printAll() {
7. for (int i = 0; i <names.size(); i++) {
8. System.out.print(names.get(i) +“ “);
9. }
10. }
11. public static void main(String[] args) {
12. final NameList sl = new NameList();
13 .for(int i=0;i<2;i++) {
14. new Thread() {
15. public void run() {
16. sl.add(”A”);
17. sl.add(”B”);
18. sl.add(”C”);
19. sl.printAll();
20. }
21. }.start();
22. }
23. }
24. }
Which two statements are true if this class is compiled and run?
(Choose two.)
A. An exception may be thrown at runtime.
B. The code may run with no output, without exiting.
C. The code may run with no output, exiting normally.
D. The code may rum with output “A B A B C C “, then exit.
E. The code may rum with output “A B C A B C A B C “, then exit.
F. The code may ruin with output “A A A B C A B C C “, then exit.
G. The code may ruin with output “A B C A A B C A B C “, then exit.


答案是EG
E我是理解的,只是G……

哪位大侠能帮忙解释一下?感激不尽……

------解决方案--------------------
可能是这样线程1在增加了ABC之后在printALL的过程中,线程2增加了另一组ABC,所以线程1执行printALL的结果并不是线程1本身所增加的那些字符