/*
 * Chopstick.java
 *
 * The dining philosophers problem solved using synchronization
 *
 * copyright (c) 2000, 2001, 2002, 2010 - Russell C. Bjork
 *
 */

package philosophers;
import javax.swing.JLabel;

/** Simulation of a chopstick */

public class Chopstick
{
    /** Constructor
     *
     *  @param label a label into which to write the name of the current owner
     */
     
    public Chopstick(JLabel label)
    {
        this.label = label;
        owner = null;
    }
    
    /** Pick up this chopstick
     *
     *  @param who the philosopher who wants it - should be made to wait until
     *         it is available, if necessary.
     */
     
    public synchronized void pickup(Philosopher who)
    {
        while (owner != null)
            try
            {
                wait();
            }
            catch(InterruptedException e)
            { }
            
        // Claim ownership of the chopstick
        
        owner = who;

        // Show on the screen who has this chopstick
        
        label.setText(owner.name());
    }
    
    /** Put down this chopstick.  The caller should be the owner of this 
        chopstick. */
    
    public synchronized void putdown()
    {
        // Surrender ownership of the chopstick
        
        owner = null;

        // Show on the screen that no one has this chopstick
        
        label.setText("(None)");
        
        notify();
    }

    // Instance variable passed to constructor
    
    private JLabel label;
    
    // Philosopher who currently has this chopstick
    
    private Philosopher owner;
}
