import java.lang.Thread; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockedValues { //This is the shared object we are controlling access to private int theValA; private int theValB; /* * This is the lock we are using to control shared access. Passing a value * of true tells the ReadWriteLock to fairly allocate the locks. */ private ReentrantReadWriteLock theLock = new ReentrantReadWriteLock(true); public LockedValues() { // Initialise theVal with an initial value theValA = 12; theValB = 21; } private void testLocking() { /* * These are the threads that will simultaniously attempt to access the shared object */ theReader r1 = new theReader("One"); theReader r2 = new theReader("Two"); theReader r3 = new theReader("Three"); theWriter w1 = new theWriter("A", 111111, 1010); //theWriter w2 = new theWriter("B", 222222); //theWriter w3 = new theWriter("C", 333333); Thread tr1 = new Thread(r1); tr1.start(); //new Thread(w2).start(); new Thread(r2).start(); //new Thread(w3).start(); new Thread(w1).start(); new Thread(r3).start(); } // The main public static void main(String[] args) { LockedValues lv = new LockedValues(); lv.testLocking(); } /** * A Reader is attempting to access, * gets the value, and prints the result. It Sleeps for 1 second while * holding the lock to simulate a long running operation. */ private class theReader implements Runnable { private String name; public theReader(String theName) { name = theName; } public void run() { try { //theLock.readLock().lock(); int value1 = theValA; int value2 = theValB; System.out.println("The Reader: " + name + " - " + value1 + ", " + value2); try { Thread.sleep(1); } catch (InterruptedException e) {} } finally { //theLock.readLock().unlock(); } } } /** * A Writer takes a value, and updates the value, * and then prints the result. It Sleeps for 2 seconds while * holding the lock to simulate a more long running operation. */ private class theWriter implements Runnable { private String name; private int value1; private int value2; public theWriter(String theName, int theValue1, int theValue2) { name = theName; value1 = theValue1; value2 = theValue2; } public void run() { try { theLock.writeLock().lock(); theValA = value1; theValB = value2; System.out.println("The Writer " + name + " - "+ value1 + ", " + value2); try { Thread.sleep(2000); } catch (InterruptedException e) {} } finally { theLock.writeLock().unlock(); } } } }