import java.lang.Thread; public class RW { //This is the shared object we are controlling access to private int theVal; private Semaphore S = new Semaphore(1); public RW() { theVal = 12; } private void test() { theReader r1 = new theReader("One"); theReader r2 = new theReader("Two"); theReader r3 = new theReader("Three"); theWriter w1 = new theWriter("A", 111111); theWriter w2 = new theWriter("B", 222222); Thread tr1 = new Thread(r1); tr1.start(); new Thread(w1).start(); new Thread(w2).start(); new Thread(r2).start(); new Thread(r3).start(); } // The main public static void main(String[] args) { RW rw = new RW(); rw.test(); } private class theReader implements Runnable { private String name; public theReader(String theName) { name = theName; } public void run() { try { S.P(); int value = theVal; System.out.println("The Reader " + name + " with a value " + value); try { Thread.sleep(1000); } catch (InterruptedException e) {} } finally { S.V(); } } } private class theWriter implements Runnable { private String name; private int value; public theWriter(String theName, int theValue) { name = theName; value = theValue; } public void run() { try { S.P(); theVal = value; System.out.println("The Writer " + name + " with the value "+ value); try { Thread.sleep(1000); } catch (InterruptedException e) {} } finally { S.V(); } } } }