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這三個方法都要變成同步的方法。

Comments

Popular posts from this blog

Android-使用webview在V3版的Google地圖GPS定位