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,题的意思也没看明白,我应该怎样测试这个代码段呢,
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,题的意思也没看明白,我应该怎样测试这个代码段呢,
如果setXY()方法没有加上Synchronized(同步)关键字,其它线程调用此方法也会有可能使check()方法返回true.
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();
}
}
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.