/* Manna-Pnueli mutual exclusion algorithm */
class MannaPnueli {
    /* Number of processes currently in critical section */
    static volatile int inCS = 0;
    /* Process p wants to enter critical section */
    static volatile int wantp = 0;
    /* Process q wants to enter critical section */
    static volatile int wantq = 0;
    
    
    static class P extends Thread {
        public void run() {
            while (true) {
//		synchronized(MannaPnueli.class) {
		if (wantq == -1)
		    wantp = -1;
		else
		    wantp = 1;
//		}
		while (wantq == wantp)
		    Thread.yield();
		/* Non critical section */
		inCS++;
                Thread.yield();
                /* Critical section */
                if (inCS != 1)
		    System.exit(1);
		inCS--;
		wantp = 0;
            }
        }
    }

    static class Q extends Thread {
        public void run() {
	    while (true) {
//		synchronized(MannaPnueli.class) {
		if (wantp == -1)
		    wantq = 1;
		else
		    wantq = -1;
//		}
		while (wantp == -wantq)
		    Thread.yield();		
		inCS++;
                Thread.yield();
                /* Critical section */
                if (inCS != 1)
		    System.exit(1);
		inCS--;
		wantq = 0;
            }
        }
    }
    
    public static void main(String[] args) {
        Thread p = new P();
        Thread q = new Q();
	p.start();
	q.start();
    }
}
