import java.util.concurrent.Semaphore; class Sync { public static Semaphore ReadSema = new Semaphore(0); public static Semaphore WriteSema = new Semaphore(1); } class Writer implements Runnable { private String msg; public Writer(String s) { msg = s; } // Interface method public void run() { while ( true ) { try { Sync.WriteSema.acquire(); } catch ( InterruptedException e ) { } System.out.println(msg+".. writing"); Sync.ReadSema.release(); } } } class Reader implements Runnable { private String msg; public Reader(String s) { msg = s; } // Interface method public void run() { while ( true ) { try { Sync.ReadSema.acquire(); } catch ( InterruptedException e ) { } System.out.println(msg+".. reading"); Sync.WriteSema.release(); } } } public class ThreadDemo2 { public static void main(String args[]) throws InterruptedException { Runnable r, w; Thread t1, t2; r = new Reader("Read"); w = new Writer("Write"); t1 = new Thread(r); t2 = new Thread(w); t1.start(); t2.start(); System.out.println("Waiting for threads to exit"); t1.join(); t2.join(); System.out.println("Done"); } }