package diningphilosophers4;

import java.util.concurrent.Semaphore;

/**
 * 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 String name;

	private Semaphore available = new Semaphore(1);
	
	/**
	 * 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.
	 */
	void put() {
		available.release();
	}

	/**
	 * ChopStick aufnehmen. Falls es nicht verfuegbar ist wird gewartet.
	 * @throws java.lang.InterruptedException
	 */
	void get() throws java.lang.InterruptedException {
		available.acquire();
	}
	
	boolean tryToGet() throws java.lang.InterruptedException {
		return available.tryAcquire();
	}
	
	public String toString() {
		return name;
	}
}
