User Tools

Site Tools


sleeping-barber

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
sleeping-barber [2007/10/23 23:10] francksleeping-barber [2007/10/29 20:51] (current) cs253184
Line 22: Line 22:
 ''Customer i leaves''. ''Customer i leaves''.
  
 +An applet of this problem can be found
 +[[http://colos1.fri.uni-lj.si/%7Ecolos/Colos/EXAMPLES/MARIBOR/barber|here]].
 +
 +<code java>
 +public class Barber extends Thread 
 +{
 +  public void run()
 +  {
 +    while (true)
 +    {
 +      while (shop.isEmpty())
 +      {
 +        try
 +        {
 +          this.wait();
 +        }
 +        catch (InterruptedException e) {}
 +      }
 +    }
 +  }
 +}
 +</code>
 +<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("Customer " + this.id + " enters");
 +      int number = shop.getChair();
 +      if (number != -1)
 +      {
 +        System.out.println("Customer " + this.id + " sits down");
 +        while (!shop.isFirst(number))
 +        {
 +          try
 +          {
 +            this.wait();
 +          }
 +          catch (InterruptedException e) {}
 +        }
 +        System.out.println("Customer " + this.id + " gets a haircut");
 +        while (!shop.isDone())
 +        {
 +          try
 +          {
 +            this.wait();
 +          }
 +          catch (InterruptedException e) {}
 +        }
 +      }
 +      System.out.println("Customer " + this.id + " leaves");
 +    }
 +  }
 +}
 +</code>
 +
 +<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;
 +  }
 +}
 +</code>
 +
 +Another sketch of a solution can be found
 +[[http://www.cse.yorku.ca/~franck/teaching/2002-03/6490A/0502.html|here]].
 +
 +Slawomir's running (!!!) solution can be found [[discussion|here]].
sleeping-barber.1193181012.txt.gz · Last modified: 2007/10/23 23:10 by franck

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki