1,public class SychTest{ 
 private int x; 
 private int y; 
 public void setX(int i){ x=i;} 
 public void setY(int i){y=i;} 
 public Synchronized void setXY(int i){ 
   setX(i); 
   setY(i); 
  } 
 public Synchronized boolean check(){ 
      return x!=y;   
   } 
   } 
  Under which conditions will  check() return true when called from a different class? 
 A.check() can never return true. 
 B.check() can return true when setXY is callled by multiple threads. 
 C.check() can return true when multiple threads call setX and setY separately. 
 D.check() can only return true if SychTest is changed allow x and y to be set separately. 
Answer:  c 为什么是c,题的意思也没看明白,我应该怎样测试这个代码段呢,

解决方案 »

  1.   

    题目的意思是:"当什么情况下调用 check()方法会返会true?",也就是说什么情况下 x 会不等于y 。答案 C 说:"当有不同的线程单独调用 setX()或setY()方法时,X会不等于Y。"这很好理解嘛,单独调用其中一个方法当然会使x不等于y,其实还不一定需要其它线程来调用,同一个线程还是一样的.
    如果setXY()方法没有加上Synchronized(同步)关键字,其它线程调用此方法也会有可能使check()方法返回true.
      

  2.   

    我这样写的测试代码是不是命题要求的意思?总感觉不太理解在考什么
    public class SychTest{ 
     private int x; 
     private int y; 
     public void setX(int i){ x=i;} 
     public void setY(int i){y=i;} 
     public synchronized void setXY(int i){ 
       setX(i); 
       setY(i); 
      } 
     public synchronized void check(){ 
           System.out.println(x);   
               System.out.println(y);   
          System.out.println(x!=y);   
       } 

     public static void main(String[] args) {
            final SychTest myt2 = new SychTest();
            Thread t1 = new Thread(
                new Runnable() {
                    public void run() {
                        myt2.setX(1);


                    }   
                }
            ); Thread t2 = new Thread(
                new Runnable() {
                    public void run() {
                        myt2.setY(2);


                    }   
                }
            );        Thread t3 = new Thread(
                new Runnable() {
                    public void run() {
                        myt2.check();
                    }   
                }
            );  
            t1.start();
            t2.start(); 
            t3.start();
        }
    }
      

  3.   

    谢谢孤小小,如果改成下面这样,答案是什么,为什么呢?
    public class SyncTest {
    private int x;
    private int y;
    public synchronized void setX (int i) {x=i;}
    public synchronized void setY (int i) {y=i;}
    public synchronized void setXY(int i)(set X(i); setY(i);)
    public synchronized Boolean check() (return x !=y;)
    )
    Under which conditions 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 only return true if SyncTest is changed to allow x and y to be set separately.