QUESTION NO: 113 
Given: 
1. public class SyncTest { 
2. private int x; 
3. private int y; 
4. private synchronized void setX( int i ) { x = i; } 
5. private synchronized void setY( int i ) { y = i; } 
6. public void setXY( int i ) { setX(i); setY(i); } 
7. public synchronized boolean check() { return x != y; } 
8. } 
 
Under which condition will check return true when called from a different class? 
 
A.  check can never return true. 
B.  check can return true when setXY is called by multiple threads. 
C.  check can return true when multiple threads call setX and setY separately. 
D.  check can return true only if SyncTest is changed to allow x and y to be set 
separately. 
 
 
Answer: B 不好意思,只剩0分,没得给大家。

解决方案 »

  1.   

    当然是B啦
    在调用setXY时,如果线程A运行了setX,但还未开始运行setY时,线程A由于时间片用完暂时让给另外一个线程B运行,这个时候如果线程B执行check就返回true所以A是错误的,C也是错误的(不可能调用private方法),D也是错误的
      

  2.   

    说得有点不清楚,应该是在线程A调用setXY时,如果运行了setX,但还未开始运行setY时,线程A由于时间片用完暂时让给另外一个线程B运行,这个时候如果线程B执行check就返回true
      

  3.   

    楼上说的情形是“临时性”的,还有一种“永久性”的:在线程A调用setXY时,如果运行了setX,但还未开始运行setY时,线程A由于时间片用完暂时让给另外一个线程B运行,而线程B以不同于A的参数调用setXY,等线程B从setXY返回后,线程A恢复运行,执行了setY。此后如果没有人再调用setXY的话,check就永远返回true了。(不好意思,借用了楼上的很多文字 :)