//readers-writer //args: public class readers_writer { static java.util.Random rand; static {rand = new java.util.Random(System.currentTimeMillis());} public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: prod_cons prod_random cons_random"); System.exit(1); } int prodrand = Integer.parseInt(args[0]); int consrand = Integer.parseInt(args[1]); SharedMemory shmem = new SharedMemory(); new Writer(shmem,prodrand); new Reader(shmem,consrand); new Reader(shmem,consrand); new Reader(shmem,consrand); } } class SharedMemory { private int readers; private boolean writer_has; private static class Writing {} Writing writing = new Writing(); //list of waiting readers //synch'ed so only one writer at a itme public synchronized void write() { writer_has = true; System.out.println("write IN"); try { Thread.sleep(300); //pause so some reader(s) can wait } catch (InterruptedException e) {} /* if (readers > 0) try { System.out.println("Writer waiting..."); wait(); } catch (InterruptedException e) { System.out.println("Writer interrupted"); } */ synchronized (writing) { writing.notifyAll(); //tell all waiting readers } writer_has = false; System.out.println("write OUT"); } public void read() { System.out.println("read IN"); while (writer_has) { System.out.println("Reader waiting..."); try { synchronized (writing) { writing.wait(); } } catch (InterruptedException e) {} } System.out.println("read OUT"); } } //needs exclusive access to shared memory object class Writer implements Runnable { SharedMemory shmem; int randwait; Writer(SharedMemory shmem, int prodrand) { this.shmem = shmem; this.randwait = prodrand; System.out.println("Writer running: "); new Thread(this,"Writer").start(); } public void run() { int worktime; while (true) { try { worktime = prod_cons.rand.nextInt(randwait); System.out.println("Writer work: "+worktime); Thread.sleep(worktime); } catch (InterruptedException e) { System.out.println("Writer sleep interrupted"); } shmem.write(); } } } //readers can have simultaneous access to shared memory object class Reader implements Runnable { SharedMemory shmem; int randwait; Reader(SharedMemory shmem, int consrand) { this.shmem = shmem; this.randwait = consrand; System.out.println("Reader running: "); new Thread(this,"Reader").start(); } public void run() { int worktime; while (true) { shmem.read(); try { worktime = prod_cons.rand.nextInt(randwait); System.out.println("Reader work: "+worktime); Thread.sleep(worktime); } catch (InterruptedException e) { System.out.println("Reader sleep interrupted"); } } } }