import java.lang.Thread; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockedValue2 { //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 LockedValue2() { // 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 r = new theReader(); theWriter w = new theWriter(); Thread[] tr = new Thread[3]; // thread for reader for(int i=0; i<3; i++) { tr[i] = new Thread(new theReader(i)); tr[i].start(); } Thread[] tw = new Thread[3]; // thread for reader for(int i=0; i<3; i++) { tw[i] = new Thread(new theWriter(i, i*1111)); tw[i].start(); } } // The main public static void main(String[] args) { LockedValue2 lv = new LockedValue2(); 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 int readerID; public theReader() { readerID = 0; } public theReader(int id) { readerID = id; } public void run() { try { //theLock.readLock().lock(); int value = theVal; System.out.println("The Reader " + readerID + " with a value " + value); 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 int writerID; private int value; public theWriter() { writerID = 0; value = 0; } public theWriter(int id, int theValue) { writerID = id; value = theValue; } public void run() { try { theLock.writeLock().lock(); theVal = value; System.out.println("The Writer " + writerID + " with the value "+ value); try { Thread.sleep(2000); } catch (InterruptedException e) {} } finally { theLock.writeLock().unlock(); } } } }