package diningphilosophers3;

/**
 * Klasse ChopStick, die ein Essstaebchen repraesentiert.
 * 
 * @author  Ralf Kunze (rkunze@uos.de), Institut fuer Informatik, Universitaet Osnabrueck
 * @date 14.05.2007
 */
public class ChopStick {

	private boolean available = true;
	
	private String name;

	/**
	 * Erzeugt ein ChopStick
	 * 
	 * @param name Name des ChopStick
	 */
	public ChopStick(String name) {
		this.name = name;
	}

	/**
	 * ChopStick ablegen. Alle Threads die auf dieses Objekt warten werden geweckt.
	 */
	synchronized void put() {
		available = true;
		notifyAll();
	}

	/**
	 * ChopStick aufnehmen. Falls es nicht verfuegbar ist wird gewartet.
	 * @throws java.lang.InterruptedException
	 */
	synchronized void get() throws java.lang.InterruptedException {
		while (!available) {
			wait();
		}
		available = false;
	}
	
	synchronized  boolean tryToGet() throws java.lang.InterruptedException {
		if (!available)
			return false;
		available = false; // Alternativ aufrufen der Methode get();
		return true;
	}
	
	public String toString() {
		return name;
	}
}
