java - Thread Mutual Exclusive Section -


hello had phone interview not able answer question , know answer, believe, advisable reach out answers don't know. please encourage me understand concept.

his question was:

"the synchronized block allows 1 thread time mutual exclusive section. when thread exits synchronized block, synchronized block not specify of waiting threads allowed next mutual exclusive section? using synchronized , methods available in object, can implement first-come, first-serve mutual exclusive section? 1 guarantees threads let mutual exclusive section in order of arrival? "

 public class test {    public static final object obj = new object();     public void dosomething() {      synchronized (obj) {           // mutual exclusive section      }    }  } 

here's simple example:

public class fairlock {     private int _nextnumber;     private int _curnumber;      public synchronized void lock() throws interruptedexception {         int mynumber = _nextnumber++;         while(mynumber != _curnumber) {             wait();         }     }      public synchronized void unlock() {         _curnumber++;         notifyall();     } } 

you use like:

public class example {   private final fairlock _lock = new fairlock();    public void dosomething() {     _lock.lock();     try {       // mutually exclusive here ...     } {       _lock.unlock();     }   } } 

(note, not handle situation caller lock() receives interrupted exception!)


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -