Question about the keyword synchronized

Discussion in 'Java' started by gabriel, Jul 20, 2003.

  1. gabriel

    gabriel Guest

    ¤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.
     
    gabriel, Jul 20, 2003
    #1
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.