"SCJP 1.6版考題 002" 修訂間的差異

出自 陳富國維基館
前往: 導覽搜尋
(新頁面: Given:<br>1.    public class TestSeven extends Thread{<br>2.             private static int x;<br>3.             p...)
 
(移除所有頁面內容)
行 1: 行 1:
Given:<br>1. &nbsp; &nbsp;public class TestSeven extends Thread{<br>2. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; private static int x;<br>3. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public synchronized void doThings(){<br>4. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int current = x;<br>5. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current++;<br>6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = current;<br>7. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br>8. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public void run(){<br>9. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; doThings();<br>10. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}<br>11. &nbsp;}
 
  
 
 
 
 
Which statement is true?<br>A. Compilation fails.<br>B. An exception is thrown at runtime.<br>C. Synchronizing the run() method would make the class thread-safe.<br>D. The data in variable "x" are protected from concurrent access problems.<br>E. Declaring the doThings() method as static would make the class thread-safe.<br>F. Wrapping the statements within doThings() in a synchronized(new Object()){} block would make the class thread-safe.
 
 
 
<div class="toccolours mw-collapsible mw-collapsed">
 
<span style="font-size:medium;">解答</span>
 
 
----
 
<div class="mw-collapsible-content">
 
<span style="font-size: medium;">Ans: E  </span>
 
 
<span style="font-size:medium;"> 解說:
 
E是說若宣告doThings方法為靜態的方法將使得該類別為"執行緒安全"。
 
<br>
 
&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp;thread-safe是說不管執行緒如何執行,都不會破壞掉類別資料完整性。
 
<br>
 
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;若方法是物件的成員,則多個執行緒就可以執行多個版本的doThings方法,好像多人一起操作一個共同的整數資料x(因為x是靜態的/類別的,只有一個),
 
<br>
 
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;若是把doThings方法變成類別,那麼也就只有一個版本的doThings方法,加上此方法又是同步的,同一時間只有此方法可以對x進行操作,不會因為多人方法的存取x而造成x的破壞。
 
 
</span>
 
</div></div>
 
{{SCJP 1.6版考題講解}}
 

於 2013年3月26日 (二) 06:59 的修訂