首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

一路线程的题目,头痛。

2011-12-22 
一道线程的题目,头痛。。。classNameList{privateListnamesnewArrayList()publicsynchronizedvoidadd(Strin

一道线程的题目,头痛。。。
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



[解决办法]
这样来的 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

竖线是两个线程打印的内容

------解决方案--------------------


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

热点排行