Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the original librarian problem you described, the problem doesn't care which student is in which room, therefore uses a simple thread safe counter (i.e. a Semaphore) to implement control of the resources. Following that description of the problem there still needs to be an alteration of your implementation. One approach is to 2 methods on the librarian class, one for requesting the SME, the other for returning it.</p> <pre><code>class Librarian { Semaphore sme = new Semaphore(NUMBER_OF_SMES); void requestSme() throws InterruptedException { sme.acquire(); } void releaseSme() { sme.release(); } } class Student { Librarian librarian; public void run() { libarian.requestSme(); try { // Do something finally { librarian.releaseSme(); } } } </code></pre> <p>However if you do need to know which Student is working with which SME, then you need a different construct for managing the resources, a Semaphore is no longer sufficient. One example could be a Queue.</p> <pre><code>class Librarian { BlockingQueue&lt;SubjectMatterExpert&gt; q = new ArrayBlockingQueue&lt;SubjectMatterExpert&gt;(NUMBER_OF_SMES); public Librarian() { for (int i = 0; i &lt; NUMBER_OF_SMES; i++) q.put(new SubjectMatterExpert(String.valueOf(i)); } SubjectMatterExport requestSme() throws InterruptedException { q.take(); } void releaseSme(SubjectMatterExpert toRelease) { q.put(toRelease); } } class Student { Librarian librarian; public void run() { SubjectMatterExpert sme = libarian.requestSme(); try { System.out.println("Student: " + this + ", SME: " sme); finally { if (sme != null) librarian.releaseSme(sme); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload