import java.lang.Thread; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockedValue { //This is the shared object we are controlling access to private int theVal; /* * 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 LockedValue() { // Initialise theVal with an initial value theVal = 12; } 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); 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) { LockedValue lv = new LockedValue(); 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 value = theVal; System.out.println("The Reader " + name + " with a value " + value); try { Thread.sleep(10000); } 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 value; public theWriter(String theName, int theValue) { name = theName; value = theValue; } public void run() { try { theLock.writeLock().lock(); theVal = value; System.out.println("The Writer " + name + " with the value "+ value); try { Thread.sleep(10); } catch (InterruptedException e) {} } finally { theLock.writeLock().unlock(); } } } }