Description: First on the code, note follow-up supplement.
public class LockTest2 {
Private Reentrantreadwritelock lock = new Reentrantreadwritelock ();
public static void Main (string[] args) {
Final Countdownlatch latch = new Countdownlatch (2);
Long startTime = System.currenttimemillis ();
Final LockTest2 test = new LockTest2 ();
Thread thread1 = new Thread (new Runnable () {
@Override
public void Run () {
Test.superget (Thread.CurrentThread ());
Latch.countdown ();
}
}, "Thread1");
Thread thread2 = new Thread (new Runnable () {
@Override
public void Run () {
Test.superget (Thread.CurrentThread ());
Latch.countdown ();
}
}, "Thread2");
Thread1.start ();
Thread2.start ();
try {
Latch.await ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Long endTime = System.currenttimemillis ();
Long result = Endtime-starttime;
SYSTEM.OUT.PRINTLN ("Total time-consuming" +result);
}
After the improved get
private void Superget (thread thread) {
try {
Lock.readlock (). Lock ();
Lock.writelock (). Lock (); This ≈synchronized
Long start = System.currenttimemillis ();
while (System.currenttimemillis ()-start <= 1) {
System.out.println (Thread.getname () + "performing read operation");
}
System.out.println (Thread.getname () + "read operation completed");
} catch (Exception e) {
E.printstacktrace ();
} finally {
Lock.readlock (). Unlock ();
}
}
Private synchronized void get (thread thread) {
Long start = System.currenttimemillis ();
while (System.currenttimemillis ()-start <= 1) {
System.out.println (Thread.getname () + "performing read operation");
}
System.out.println (Thread.getname () + "read operation completed");
}
}
Java Concurrent Programming 6