import java.util.concurrent.Semaphore; public class TestSemaphore { public static void main(String[] args){ SharedData sd = new SharedData(); NitA na = new NitA(sd); na.start(); NitB nb = new NitB(sd); nb.start(); } } class SharedData { public int x; public int y; public int z; public Semaphore xySem = new Semaphore(0); public Semaphore zSem = new Semaphore(0); } class NitA extends Thread { public NitA(SharedData data){ sd = data; } protected SharedData sd; public void run(){ int i = 0; while(true){ i++; sd.x = i; sd.y = i*i; sd.xySem.release(); try { sd.zSem.acquire(); } catch (InterruptedException e) {} System.out.println( sd.x + " + " + sd.y + " = " + sd.z); if (i == 10) System.exit(0); } } } class NitB extends Thread{ public NitB(SharedData data){ sd = data; } protected SharedData sd; public void run(){ while(true){ try { sd.xySem.acquire(); } catch (InterruptedException e) {} sd.z = sd.x + sd.y; sd.zSem.release(); } } }