Question 1261. 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.   

    因为采用了线程同步(synchronized  方法),所以三个线程的最终结果都会写到arraylist中,不存在冲掉或者覆盖之类的问题,所以最终一定有三个a,三个b三个c。当然顺序是不确定的,所以EG均可能。
      

  2.   

    5天后我就考SCJP考试了!!!麻烦各位大侠帮忙解决疑惑!!!感激不尽!~~~
      

  3.   

    A A B C A A B C B C
    A A B B C A A B B C C 
    我也是初学者,这是在我的机子上测试得出的结果之一,我认为不会得出答案F. The code may ruin with output “A A A B C A B C C “, then exit. 当然答案D不在考虑范围。这个题目是不是要用排除法呢
      

  4.   

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

  5.   

    给你一个程序,希望你可以理解。如果还是理解不了,那么就好好在看看基础吧。这个程序演示了为什么会出现4个Aimport java.util.ArrayList;
    import java.util.List;public class Main { private List names = new ArrayList(); public synchronized void add(String name) {
    names.add(name);
    } public synchronized void printAll() {
    for (int i = 0; i < names.size(); i++) {
    System.out.print(names.get(i) + " ");
    }
    }
    static int j = 0;
    public static void main(String[] args) {

    final Main sl = new Main();
    for (int i = 0; i < 2; i++) {
    if (i == 0) {
    j = 0;
    } else {
    j = 1;
    }

    Thread t = new Thread() {
    public void run() {
    sl.add("A" + j);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
    sl.add("B" + j);
    sl.add("C" + j);
    sl.printAll();
    System.out.println("===");
    }
    };
    t.start();
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    }
    }
    }
    }
      

  6.   

    可能是这样线程1在增加了ABC之后在printALL的过程中,线程2增加了另一组ABC,所以线程1执行printALL的结果并不是线程1本身所增加的那些字符
    --------
    他的这个答案是错误的,不知道你是如何理解的。