class NameList {
   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) +" ");
       }
   }
   
   public static void main(String[] args) {
      final NameList sl = new NameList();
      for(int i=0;i<2;i++) {
          new Thread() {
             public void run() {
                sl.add("A");
                sl.add("B");
                sl.add("C");
                sl.printAll();
             }
           }.start();
     }
  }
}
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

解决方案 »

  1.   

    z_lping:
    可以回答下么?谢谢。。
      

  2.   

    ABCDF显然错,有疑问吗?
    E:线程1add完毕,printAll,线程2add完毕,printAll
    G:线程1add完毕,线程2add("A"),线程1printAll,线程2add完毕,printAll以上只是列举一种可能情况
      

  3.   

    G:线程1add完毕,线程2add("A"),线程1printAll,线程2add完毕,printAll
    ==========================================================================
    线程2add("A")以后,等到线程1printAll以后,线程2不是add么?
    如果是的话不是从sl.add("B");开始了阿??
    那么“A B C A A B C A B C “, 里面的第3个A怎么来的阿?
      

  4.   

    另外
     for(int i=0;i<2;i++)
    不是只执行i = 0  i = 1的两次啊??
    怎么会有那么多的输出啊...
      

  5.   

    这样来的 names list里面的数据是这样的
    线程0执行ADD
    A B C  ===> 线程1执行ADD(A)
    name 变为 A B C A   ===>  线程0执行打印 A B C A ====>线程1完成插入 =====>再打印A B C A | A B C A B C竖线是两个线程打印的内容
      

  6.   

    第一次打印s1内容:ABCA
    然后add("B")add("C"),第二次打印s1内容:ABCABC