Content: Shared when reading a lock, the mutex (visible running result) is implemented by AQS.
public class Reentrantreadwritelocktest {static class MyObject {private Object object;private readwritelock lock = new Ree Ntrantreadwritelock ();p ublic void Get () {Lock.readlock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "ready to read Data!"); try {thread.sleep (New Random (). Nextint (1000)); System.out.println (Thread.CurrentThread (). GetName () + "read data:" + This.object);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.readlock (). Unlock ();}} public void put (Object object) {Lock.writelock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "prepare to write Data"), try {thread.sleep (New Random (). Nextint (1000)); This.object = object; System.out.println (Thread.CurrentThread (). GetName () + "Write data for" + This.object);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.writelock (). Unlock ();}} public static void Main (string[] args) throws Interruptedexception {final MyObject MyObject = new MyObject (); Executorservice executor = Executors.newcachedthreadpool (); for (int i = 0; I < 3; i++) {Executor.execute (new Runnable () {@Overridepublic void Run () {for (int j = 0; J < 5; j + +) Myobject.put (new Random () . Nextint (1000));});} for (int i = 0; i < 3, i++) {Executor.execute (new Runnable () {@Overridepublic void Run () {for (int j = 0; J < 5; J + +) ) Myobject.get ();}});} Executor.shutdown ();}}
Operation Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A simple example of java-reentrantreadwritelock