// stand alone version of j.n.magee 11/11/96 // by mh 19/03/03 // only text user interface class Counter { int value=0; Counter(int init) { value = init; } void increment() { int temp = value; //read[v] Simulate.interrupt(); value=temp+1; //write[v+1] } int get () { return value; } } // class Counter class Simulate { public static void interrupt() { if (Math.random() < 0.5) try { Thread.sleep(200);} catch(InterruptedException e){}; //used instead of Thread.yield() to ensure portability } } // class Simulate class Turnstile extends Thread { private Counter people; private Semaphore mutex; Turnstile (Semaphore sema, Counter c) { mutex=sema; people = c; } public void run() { for (int i=1;i<=GardenTuiSema.MAX;i++){ mutex.down(); // get mutual exclusion people.increment(); mutex.up(); // release mutual exclusion } } } // class Turnstile public class GardenTuiSema { final static int MAX = 20; public static void main (String[] argv) { Counter counter = new Counter(0); Semaphore mutex = new Semaphore(1); Turnstile west= new Turnstile(mutex,counter); Turnstile east= new Turnstile(mutex,counter); System.out.println(" -- begin of garden using semaphore -- "); west.start(); east.start(); try { west.join(); east.join(); System.out.println("total count: " + counter.get()); } catch (Exception e) {} System.out.println(" -- end of garden using semaphore -- "); } } // class GardenTui