Package Com.java.concurrent;import Java.util.concurrent.locks.readwritelock;import Java.util.concurrent.locks.ReentrantReadWriteLock; Public classTestreadwritelock { Public Static voidMain (string[] args) {final Readwritelockdemo rw2=NewReadwritelockdemo (); NewThread (NewRunnable () { Public voidrun () {Try{Thread.Sleep ( -); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } rw2.Set( -); } },"Write:"). Start (); NewThread (NewRunnable () { Public voidrun () { while(true) rw2.Get(); } },"Read"). Start (); }}classReadwritelockdemo {Private intNumber =0; //define a read-write lock PrivateReadwritelockLock=NewReentrantreadwritelock (); //Read Public void Get() { //Add read lock Lock. Readlock ().Lock(); Try{System. out. println (Thread.CurrentThread (). GetName () +":"+Number ); } finally { Lock. Readlock (). Unlock (); } } //Write Data Public void Set(intNumber ) { //Create a write lock Lock. Writelock ().Lock(); Try{System. out. println (Thread.CurrentThread (). GetName () +":"+Number ); This. Number =Number ; }finally{ Lock. Writelock (). Unlock (); } }}
Java read-write lock Readwritelock