Question 126
Click the Exhibit button. 
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 ruin() { 
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
Answer: EGE选项我可以理解,是分两次进行输出的:
1. ABC
2. ABCABC
但是G选项怎么回事呢?如何会有中间那两个A连续输出呢?
我想是不是两次输出是:
1. ABCA//循环中i = 0,时,连续三个add后并没有直接printAll,而是进行i = 1时的add(“A”),再进行循环0时的printAll();
2. ABCABC//继续循环i = 1时余下的两个add(),最后输出:ABCABC.如果这样的猜想是正确的话,那我想是不是还可以这样输出啊:
㈠ABCAB  ABCABC:
㈡: ABCABC  ABCABC
只是可惜了,我在eclipse里测试时只有E选项的输出,没有出现过G的情况,小弟不才,想请大家说说我的理解行得通吗?谢谢….

解决方案 »

  1.   

    看起来楼主在准备310-055吧 -  - 你的猜想是正确的,就是这样理解的,后面两种都是可能的至于测试不出,那没办法,你控制不了CPU SCJP的题不用太过认真去琢磨~
      

  2.   

    ABCA时打印
    ABCABC时打印只要两次打印都是ABCABC的子列就有可能
      

  3.   


    嗯,这是个好方法来判定.只不过还得加上
    至少要覆盖“ABC”才可以哦.呵呵,谢谢...
      

  4.   

    很简单的 g可以看成 abca-abcabc 两次