In the absence of a write operation, two threads read one resource at a time without any problems, allowing multiple threads to read shared resources at the same time.
However, if a thread wants to write these shared resources, there should be no other thread reading or writing the resource.
Simply put, when multiple threads operate the same resource simultaneously, read-only coexistence, write-write does not coexist, and read and write do not coexist.
The lock rules for read and write locks are as follows:
After a read lock is obtained, other threads can obtain a read lock and cannot acquire a write lock
When a write lock is obtained, no other thread can obtain a read lock or a write lock
.
ImportJava.util.concurrent.locks.ReadWriteLock;ImportJava.util.concurrent.locks.ReentrantReadWriteLock;/*** Read/write lock. */ Public classReadwritelockdemo { Public Static voidMain (string[] args) {ReadWrite ReadWrite=NewReadWrite (); for(inti=0;i<5;i++) { NewThread (NewRunnable () {@Override Public voidrun () {readwrite.get (); }}). Start (); NewThread (NewRunnable () {@Override Public voidrun () {readwrite.set (); }}). Start (); } }} classReadWrite {PrivateReadwritelock readwritelock=NewReentrantreadwritelock (); /*** Perform a "read" Operation*/ Public voidget () {Try{readwritelock.readlock (). Lock (); System.out.println ("Thread" +thread.currentthread (). GetName () + "to read. "); Thread.Sleep (2*1000); }Catch(interruptedexception e) {e.printstacktrace (); }finally{readwritelock.readlock (). Unlock (); System.out.println ("Thread" +thread.currentthread (). GetName () + "finished reading. "); } } /*** "Write" Operation*/ Public voidset () {Try{readwritelock.writelock (). Lock (); System.out.println ("Thread" +thread.currentthread (). GetName () + "write. "); Thread.Sleep (2*1000); }Catch(interruptedexception e) {e.printstacktrace (); }finally{readwritelock.writelock (). Unlock (); System.out.println ("Thread" +thread.currentthread (). GetName () + "write complete. "); } } }
The sample results are as follows:
thread Thread-0 to read. Threads thread -0 Read finished. Threads thread -1 writes. Threads thread -1 write complete. Threads thread -5 writes. Threads thread -5 write complete. Threads thread -3 writes. Threads thread -3 write complete. Threads thread -7 writes. Threads thread -7 write complete. Threads thread -9 writes. Threads thread -9 write complete. Threads thread -2 for reading. Threads thread -4 for reading. Threads thread -6 for reading. Threads thread -8 for reading. Threads thread -2 Read finished. Threads thread -6 Read finished. Threads thread -8 Read finished. Thread -4 read completed.
Java Concurrency: Read-write lock Readwritelock