package geneticAnt; // Classical Semaphores in Java, I hope public class Semaphore { private int n; // the counter // For debugging: private boolean debug = false; private String name = ""; private long sem_num; public Semaphore() { n = 0; } public Semaphore(int n) { this.n = n; } public Semaphore(int n, boolean debug, String name) { this.n = n; this.debug = debug; this.name = name; if (debug) { String who = Thread.currentThread().getName(); sem_num = Math.round(Math.random()*100.00); System.out.println("In " + who + " Sem " + name + sem_num + " is created. Init to " + n); } } public Semaphore(int n, boolean debug) { this(n, debug, ""); } public synchronized void P() { String who = Thread.currentThread().getName(); if (debug) System.out.println("In sem " + name + sem_num + ", " + who + " wants a resource"); n--; if (n < 0) try { if (debug) System.out.println(who + " will wait"); wait(); } catch (InterruptedException e){} ; if (debug) System.out.println(who + " gets a resource"); } public synchronized void V() { String who = Thread.currentThread().getName(); if (debug) System.out.println("In sem " + name + sem_num + ", " + who + " releases a resource"); n++; if (n <= 0 ) if (debug) System.out.println("Sem " + name + sem_num + " is notifiying"); notify(); } }