java 线程 synchronized

来源:百度知道 编辑:UC知道 时间:2024/09/24 14:12:40
Given:
1. public class SyncTest (
2. private int x;
3. private int y;
4. private synchronized void setX (int i) (x=1;)
5. private synchronized void setY (int i) (y=1;)
6. public void setXY(int 1)(set X(i); setY(i);)
7. public synchronized Boolean check() (return x !=y;)
8. )
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.
期待高手解答!
private synchronized void setX(int i) {x=i;}//这里是i
private synchronized void setY(int i) {y=i;} //这里是i

B. Check() can return true when setXY is called by multiple threads.
假设thread1调用setXY,执行set X(i)完毕然后thread2调用check(),那结果就是true了
其中synchronized是对地4,5,7行的3个方法不能并发,并不包括第六行的setXY方法

C:因为只有分别调用setX和setY才能改变x和Y,此时再调用check()

A

你的代码有问题,是肯定过不了的
1. public class SyncTest (
2. private int x;
3. private int y;
4. private synchronized void setX (int i) (x=1;)
5. private synchronized void setY (int i) (y=1;)
6. public void setXY(int 1)(set X(i); setY(i);) //这句编译都通不过
7. public synchronized Boolean check() (return x !=y;)
8. )