sleeping-barber
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
sleeping-barber [2007/10/23 23:10] – franck | sleeping-barber [2007/10/29 20:51] (current) – cs253184 | ||
---|---|---|---|
Line 22: | Line 22: | ||
'' | '' | ||
+ | An applet of this problem can be found | ||
+ | [[http:// | ||
+ | |||
+ | <code java> | ||
+ | public class Barber extends Thread | ||
+ | { | ||
+ | public void run() | ||
+ | { | ||
+ | while (true) | ||
+ | { | ||
+ | while (shop.isEmpty()) | ||
+ | { | ||
+ | try | ||
+ | { | ||
+ | this.wait(); | ||
+ | } | ||
+ | catch (InterruptedException e) {} | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | <code java> | ||
+ | public class Customer extends Thread | ||
+ | { | ||
+ | private int id; | ||
+ | private Shop shop; | ||
+ | |||
+ | public Customer(int id) | ||
+ | { | ||
+ | super(); | ||
+ | this.id = id; | ||
+ | } | ||
+ | |||
+ | public void run() | ||
+ | { | ||
+ | while (true) | ||
+ | { | ||
+ | System.out.println(" | ||
+ | int number = shop.getChair(); | ||
+ | if (number != -1) | ||
+ | { | ||
+ | System.out.println(" | ||
+ | while (!shop.isFirst(number)) | ||
+ | { | ||
+ | try | ||
+ | { | ||
+ | this.wait(); | ||
+ | } | ||
+ | catch (InterruptedException e) {} | ||
+ | } | ||
+ | System.out.println(" | ||
+ | while (!shop.isDone()) | ||
+ | { | ||
+ | try | ||
+ | { | ||
+ | this.wait(); | ||
+ | } | ||
+ | catch (InterruptedException e) {} | ||
+ | } | ||
+ | } | ||
+ | System.out.println(" | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code java> | ||
+ | public class Shop | ||
+ | { | ||
+ | private Barber barber; | ||
+ | |||
+ | public final int NUMBER_OF_CHAIRS = 8; | ||
+ | |||
+ | private int first; | ||
+ | private int next; | ||
+ | private boolean done; | ||
+ | |||
+ | public synchronized int getChair() | ||
+ | { | ||
+ | if (this.next - this.first > Shop.NUMBER_OF_CHAIRS) | ||
+ | { | ||
+ | return -1; | ||
+ | } | ||
+ | else | ||
+ | { | ||
+ | this.notifyAll(); | ||
+ | return last++; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public synchronized boolean isFirst(int number) | ||
+ | { | ||
+ | return this.first == number; | ||
+ | } | ||
+ | |||
+ | public synchronized boolean isDone() | ||
+ | { | ||
+ | return this.done; | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Another sketch of a solution can be found | ||
+ | [[http:// | ||
+ | |||
+ | Slawomir' |
sleeping-barber.1193181012.txt.gz · Last modified: 2007/10/23 23:10 by franck