Posts

Showing posts from September, 2011

SCJP題庫第244題

Given: 1. public class TestSeven extends Thread{ 2.   private static int x; 3.   public synchronized void doThings(){ 4.     int current = x; 5.     current++; 6.     x = current; 7.   } 8.   public void run(){ 9.     doThings(); 10. } 11.} Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()){} block would make the class thread-safe. Ans: E 解說 : E是說若宣告doThings方法為靜態的方法將使得該類別為"執行緒安全"。 thread-safe是說不管執行緒如何執行,都不會破壞掉類別資料完整性。 若方法是物件的成員,則多個執行緒就可以執行多個版本的 doThings方法,好像多人一起操作一個共同的整數資料x(因為x是靜態的/類別的,只有一個),若是把 doThings方法變成類別,那麼也就只有一個版本的 doThings方法,加上此方法又是同步的,同一時間只有此方法可以對x進行操作,不會因為多人方法的存取x而造成x的破壞。

SCJP題庫第243題

  Given that Triangle implements Runnable, and:   31. void go() throws Exception{ 32.     Thread t = new Thread(new Triangle()); 33.     t.start(); 34.     for(int x=1; x<100000; x++){ 35.      //insert code here 36.     if(x%100 == 0) System.out.print("g"); 37. }} 38. public void run(){ 39.   try{ 40.     for(int x=1; x<100000; x++){ 41.       //insert the same code here 42.        if(x%100 == 0) System.out.print("t"); 43.     } 44. }catch(Exception e){} 45.} Which two statements, inserted independently at both lines 35 and 41, tend to allow both threads to temporarily pause and allow the other thread to execute? (Choose two.) A. Thread.wait(); B. Thread.join(); C. Thread.yield(); D. Thread.sleep(1); E. Thread.notify(); Ans: CD 解說:在第35行和41行插入那二個程式敘述,可以使得二條執行暫時性地停止並允許其他執行緖可以執行? yield的退讓的意思,一旦下yield,立刻退出CPU,進入runable狀態。 sleep是睡眠一段時間(也是離開CPU,但確保多少時間後才能進runable的狀態).。

SCJP題庫第242題

  Given: public class NamedCounter{    private final String name;    private int count;    public NamedCounter(String name){this.name = name;}    public String getName(){return name;}    public void increment(){count++;}    public int getCount(){return count;}    public void reset(){count = 0;} }     Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.) A. declare reset() using the synchronized keyword B. declare getName() using the synchronized keyword C. declare getCount() using the synchronized keyword D. declare the constructor using the synchronized keyword E. declare increment() using the synchronized keyword Ans: ACE 解說 : 題目問那三個改變應該被做出來,以調整這個類別可以在多執行緒的環境上被安全地使用? 多執行緒使用類別中的變數若有變更的情況,應該對所有這個變數的存取(讀或寫)方法以同步的方式設定。 此題count在reset與increment方法有被變更值的情況,因此連同getCount這三個方法都要變成同步的方法。

SCJP題庫第241題

Given: 1. public class Threads3 implements Runnable{ 2.   public void run(){ 3.     System.out.print("running"); 4.   } 5.    public static void main(String[] args){ 6.       Thread t = new Thread(new Threads3()); 7.       t.run(); 8.       t.run(); 9.       t.start(); 10.  } 11.} What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The code executes and prints "running". D. The code executes and prints "runningrunning". E. The code executes and prints "runningrunningrunning". Ans: E 解說 :  t.run呼叫二次是在main的執行緒上,第3次run被執行則是以執行緒t來執行。

SCJP題庫第240題

Image
  Place a Class on each method that is declared in the class. Ans: 解說:此題問左邊的方法各自是宣告在何種類別上。   

SCJP題庫第239題

  Given: 1. public class TestOne{ 2.   public static void main(String[] args) throws Exception{ 3.     T hread.sleep(3000); 4.     System.out.println("sleep"); 5.   } 6. } What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The code executes normally and prints "sleep". D. The code executes normally, but nothing is printed. Ans: C 解說 : 第3行呼叫Thread的類別方法sleep,睡眠3秒,之後繼續執行第4行

SCJP題庫第238題

  Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.) A. new Thread(){           public void run(){doStuff();}     }; B. new Thread(){          public void start(){doStuff();}     }; C new Thread(){         public void start(){doStuff();}     }.run(); D. new Thread(){          public void run(){doStuff();}     }.start(); E. new Thread(new Runnable(){          public void run(){doStuff();}     }).run(); F. new Thread(new Runnable(){          public void run(){doStuff();}     }).start(); Ans: DF 解說:題目要求那二個程式片段可以在一個分開的執行緒上執行doStuff方法。 執行緒的啟動是要呼叫start方法,若是以呼叫run來看,run方法是執行在main執行緒之上,不是分開的執行緒。

SCJP題庫第237題

Image
Ans: 解說: 題目希望輸出能為Run Run doIt,其中一個run是t執行緒執行run得來,另一個run則需在main的執行緒以t.run方法呼叫來產生。 為讓doIt輸出是最後一個,所以在呼叫t.doIt前先喚用t.join方法,這個方法可確定t的run方法執行後才執行doIt方法。 join的意思是加到某執行緒的後面。 (因為run和doIt是物件方法,不能在靜態的main直接使用run或doIt)  

SCJP題庫第236題

  Given: 1. class Computation extends Thread{ 2. 3.     private int num; 4.     private boolean isComplete; 5.     private int result; 6. 7.     public Computation(int num){this.num = num;} 8. 9.     public synchronized void run(){ 10.     result = num * 2; 11.     isComplete = true; 12.     notify(); 13.   } 14. 15.   public synchronized int getResult(){ 16.      while(!isComplete){ 17.         try{ 18.            wait(); 19.         }catch(InterruptedException e){} 20.     } 21.     return result; 22.   } 23. 24.   public static void main(String[] args){ 25.      Computation[] computations = new Computation[4]; 26.      for(int i=0; i<computations.length; i++){ 27.         computations[i] = new Computation(i); 28.         computations[i].start(); 29.      } 30.      for(Computation c : computations) 31.         System.out.print(c.getResult() + " "); 32.      } 33.   } What is the result?  

SCJP題庫第235題

  Given: 11. public class PingPong implements Runnable{ 12.   synchronized void hit(long n){ 13.     for(int i=1; i<3; i++) 14.       System.out.print(n + "-" + i + " "); 15.   } 16.   public static void main(String[] args){ 17.     new Thread(new PingPong()).start(); 18.     new Thread(new PingPong()).start(); 19.    } 20.   public void run(){ 21.      hit(Thread.currentThread().getId); 22.   } 23. } Which two statements are true? (Choose two.) A. The output could be 8-1 7-2 8-2 7-1 B. The output could be 7-1 7-2 8-1 6-1 C. The output could be 8-1 7-1 7-2 8-2 D. The output could be 8-1 8-2 7-1 7-2 Ans: CD 解說 :  run方法會去呼叫同步方法hit,二條執行緒各自有獨立的hit方法執行,i必然是依1與2的順序輸出,A答案中執行緒7先跑2再跑1是錯的,答案B出現一條執行緒6,程式只建二條執行緒不可能出現第3條執行緒。

SCJP題庫第234題

  Given: foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object. The thread foo is currently executing bar.wait(). From another thread, what provides the most reliable way to ensure that foo will stop executing wait()? A. foo.notify(); B. bar.notify(); C. foo.notifyAll(); D. Thread.notify(); E. bar.notifyAll(); F. Object.notify(); Ans: E 解說 : foo和bar是可讓其他執行緒存取的公開參考,foo參考至一個執行緒(Thread),bar是一個Object物件,執行緒foo正在執行bar.wait() 從另一個執行緒,可以提供一個最可靠的方式來確認foo可以停止執行wait方法? 由於是對bar停止wait,所以答案不是B就是E,notify與notifyAll的差異在於一個wait池中可能會有多個執行在等待bar,若單下notify,只有一個wait池中的執行緒可以離開wait池,這個執行緒未必是foo這個執行緒,而notifyAll的意思是讓所有等待bar的執行緒全數離開bar的wait池。

SCJP題庫第233題

  Given: 1. public class Threads1{ 2.   int x = 0; 3.   public class Runner implements Runnable{ 4.     public void run(){ S.        int current = 0; 6.       for(int i=0; i<4; i++){ 7.         current = x; 8.         System.out.print(current + ", "); 9.         x = current + 2; 10.     } 11.   } 12.  } 13. 14.  public static void main(String[] args){ 15.     new Threads1().go(); 16.  } 17. 18.  public void go(){ 19.     Runnable rl = new Runner(); 20.    new Thread(r1).start(); 21.    new Thread(r1).start(); 22.  } 23.} Which two are possible results? (Choose two.) A. 0, 2, 4, 4, 6, 8, 10, 6, B. 0, 2, 4, 6, 8, 10, 2, 4, C. 0, 2, 4, 6, 8, 10, 12, 14, D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14, Ans: AC 解說 : 第20與21行各新增一條執行緒,共同執行同樣的程式與資料(r1的run方法與r1物件的x物件變數), 第6~10行的迴圈共執行4次,二條執行緒若各跑4次,輸出也最多八次,D/E的答案不可能。 A/B/C選二個,觀察x變數,由於二條執行共用此

SCJP題庫第232題

  Given: 1. public class Threads5{ 2.   public static void main(String[] args){ 3.     new Thread(new Runnable(){ 4.     public void run(){ 5.       System.out.print("bar"); 6.     }}).start(); 7.   } 8. } What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The code executes normally and prints "bar". D. The code executes normally, but nothing prints. Ans: C 解說 :第3行 直接新增一個Thread物件並執行其物件方法start,並且在第4~6行加入run方法的實作,此題可以正常地執行,並印出bar字串。

SCJP題庫第231題

  Given: 11. Runnable r = new Runnable(){ 12.   public void run(){ 13.     System.out.print("Cat"); 14.   } 15. }; 16. Thread t = new Thread(r){ 17.   public void run(){ 18.     System.outprint("Dog"); 19.   } 20. }; 21. t.start(); What is the result? A. Cat B. Dog C. Compilation fails. D. The code runs with no output. E. An exception is thrown at runtime. Ans: B 解說 : 17~19的run覆蓋掉定義在12~14的run方法,執行緒被啟動後(start),會跳至run方法來執行。

SCJP題庫第230題

  Given that t1 is a reference to a live thread, which is true? A. The Thread.sleep() method can take t1 as an argument. B. The Object.notify() method can take t1 as an argument. C. The Thread.yield() method can take t1 as an argument. D. The Thread.setPriority() method can take t1 as an argument. E. The Object.notify() method arbitrarily chooses which thread to notify. Ans: E 解說:設t1是一個參考到存活執行緒的參考,何者為真? 答案E是說 Object.notify()方法任意地選擇一個執行緒進行通知,這是對的,通知有二種,第一種是notify,第二種是notifyAll,二者的差異是 notifyAll這種通知可以把所有在等待中的執行全數離開等待的狀態,而 notify一次只能有一個等待中的執行緒離開等待的狀態。(有多個執行緒同時等待一個物件的情況下)

SCJP題庫第229題

  Given: 1. public class TestFive{ 2.   private int x; 3.   public void foo(){ 4.      int current = x; 5.     x = current + 1; 6.   } 7.   public void go(){ 8.     for(int i=0; i<5; i++){ 9.       new Thread(){ 10.       public void run(){ 11.          foo(); 12.          System.out.print(x + ", "); 13.        }}.start(); 14.    }} Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)  A. move the line 12 print statement into the foo() method B. change line 7 to public synchronized void go(){ C. change the variable declaration on line 2 to private volatile int x; D. wrap the code inside the foo() method with a synchronized(this) block E. wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loop code here} Ans: AD   解說 : 此題問那二個改變,一起發生,可以保證輸出是 1, 2, 3, 4, 5,? 此類別的go方法使用迴圈產生5個執行緒,此5個執行緒的程式碼(第10~12行)呼叫foo方法,然後再印出x的值。 為了要讓輸出是1, 2, 3,

SCJP題庫第228題

  Which three will compile and run without exception? (Choose three.) A. private synchronized Object o; B. void go(){ synchronized(){/* code here */} C. public synchronized void go(){/* code here */} D. private synchronized(this) void go(){/* code here */} E. void go(){ synchronized(Object.class){/* code here */} F. void go(){ Object o = new Object(); synchronized(o){/* code here */} Ans: CEF 解說 : 此題問那三個將會編繹與無例外的執行?同步關鍵字 synchronized可以對整個方法做同步,如C,也可以對一個區塊的程式做同步,如E/F (要指定要取得的那個物件的lock) 註:E應該是錯的,在Object類別中並沒有class這個變數,有可能這題在流傳時,出了一些問題,但,回答時還是以給的答案回。

SCJP題庫第227題

  Given: 1. public class TestOne implements Runnable{ 2.   public static void main (String[] args)throws Exception{ 3.     Thread t = new Thread(new TestOne()); 4.     t.start(); 5.     System.out.pririt("Started"); 6.     t.join(); 7.     System.out.print("Complete"); 8.   } 9.   public void run(){ 10.     for(int i=0; i<4; i++){ 11.        System.out.print(i); 12.      } 13.  } 14.} What can be a result? A. Compilation fails. B. An exception is thrown at runtime. C. The code executes and prints "StartedComplete". D. The code executes and prints "StartedComplete0123". E. The code executes and prints "Started0123Complete". Ans: E 解說 :  這個類別實作了Runnable介面,實作了run方法供執行緒執行,這個類別在main的方法是一條主執行緒,後建立了t執行緒(第3行)來執行第9行的run方法,第4行t.start()方法之後,main執行緒與t執行緒同時執行,main執行緒應該還是會先於t執行緒執行第5行的輸出(印出Started),第6行下了一個指令t.join(),這個指令的意思是讓main執行緒加到t執行緒的後面(join是結合的意思),也就是,必須等t執行緒執行完(印出0123),main執行緒才會從第7行再

SCJP題庫第226題

  Which two statements are true? (Choose two.) A. It is possible to synchronize static methods. B. When a thread has yielded as a result of yield(), it releases its locks. C. When a thread is sleeping as a result of sleep(), it releases its locks. D. The Object.wait() method can be invoked only from a synchronized context. E. The Thread.sleep() method can be invoked only from a synchronized context. F. When the thread scheduler receives a notify() request, and notifies a thread, that thread immediately releases its lock. Ans: AD 解說: A. It is possible to synchronize static methods. 對靜態的方法同步是可能的。 B. When a thread has yielded as a result of yield(), it releases its locks. 當一個執行緒執行yield方法時,會釋放他的locks。 (執行yield不需要取得與釋放locks) C. When a thread is sleeping as a result of sleep(), it releases its locks. 當一個執行緒執行sleep(),會釋放其locks… (執行sleep不需要取得與釋放locks) D. The Object.wait() method can be invoked only from a synchronized context. 一個物件的wait方法只能由同步的本文中被叫用。