Question about the keyword synchronized

G

gabriel

¤p§Ì¦³¤@¨Çconcept ¤£¤Ó©ú¥Õ, §Æ±æ¦U¦ì¤H¥S¥i¥HÀ°¤@À°§U.

First please have a look on the codes below:

public class SyncTest {
private int x;
private int y;

private synchronized void setX (int i){
x=i;
}

private synchronized void setY (int i) {
y=i;
}

public void setXY(int i){
setX(i);
setY(i);
}

public synchronized Boolean check() {
return x !=y;
}
}

The question is:
Under which conditions wull check() return when called form a different
class for both two versions

A. Check() can never return true
B. Check() can retrun true when setXY is called by multiple threads
C. check() can return true when multiple threads call setX and setY
separately
D. check() can pnly return true is SyncTest is changed to allow x and y be
set separately.


After answering this question, please kindly see a similar code:

public class SyncTest {
private int x;
private int y;

private synchronized void setX (int i){
x=i;
}

private synchronized void setY (int i) {
y=i;
}

publics ynchronized void setXY(int i){
setX(i);
setY(i);
}

public synchronized Boolean check() {
return x !=y;
}
}


It is to noted that the method setXY(int i), is now declared to
synchronized.

Again The question is:
Under which conditions wull check() return when called form a different
class for both two versions

A. Check() can never return true
B. Check() can retrun true when setXY is called by multiple threads
C. check() can return true when multiple threads call setX and setY
separately
D. check() can pnly return true is SyncTest is changed to allow x and y be
set separately.

I find this question is difficult, so please kindly give some help for me.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top