This article is a summary of the study of the article on the network, thank you for your selfless sharing.
Read-write locks are important for the use of write locks, with only one entry.
Here is an example of a read-write lock use
Package Chapter2;import Java.util.concurrent.locks.readwritelock;import Java.util.concurrent.locks.reentrantreadwritelock;public class Pricesinfo {private int price1;private int price2; Private Readwritelock lock;public Pricesinfo () {Price1 = 1;price2 = 1;lock = new Reentrantreadwritelock ();} public int GetPrice1 () {Lock.readlock (). Lock (); int value = Price1;lock.readlock (). Unlock (); return value;} public void SetPrice1 (int price1) {This.price1 = Price1;} public int GetPrice2 () {Lock.readlock (). Lock (); int value = Price2;lock.readlock (). Unlock (); return value;} public void SetPrice2 (int price2) {this.price2 = Price2;} public void setprices (int price1,int price2) {lock.writelock (). Lock (); This.price1 = Price1;this.price2 = Price2; Lock.writelock (). Unlock ();}}
Package Chapter2;public class Reader implements Runnable{private pricesinfo pricesinfo;public Reader (pricesinfo Pricesinfo) {this.pricesinfo = Pricesinfo;} @Overridepublic void Run () {for (int i=0;i<10;i++) {System.out.printf ("%s:price 2:%d\n", Thread.CurrentThread (). GetName (), Pricesinfo.getprice2 ()); System.out.printf ("%s:price 1:%d\n", Thread.CurrentThread (). GetName (), Pricesinfo.getprice1 ());}}
Package Chapter2;import Java.util.random;public class Writer implements Runnable{private Pricesinfo Pricesinfo;public Writer (Pricesinfo pricesinfo) {this.pricesinfo = Pricesinfo;} @Overridepublic void Run () {for (int i=0;i<3;i++) {int p1 = new Random (). Nextint (); int p2 = new Random (). Nextint (47) *10 ; System.out.println ("Writer:attempt to modify the prices." +p1+ " price2:" +p2);p ricesinfo.setprices (P1, p2); System.out.println ("Writer:prices has been modified." +p1+ " price2:" +p2); try {thread.sleep (2);} catch (Exception e) {//Todo:handle Exception}}}
Package Chapter2;public class Main6 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-9-17 11:17:50 * @ param args */public static void main (string[] args) {Pricesinfo pricesinfo = new Pricesinfo (); Reader reader[] = new READER[5]; Thread threadsreader[] = new Thread[5];for (int i = 0; i < threadsreader.length; i++) {reader[i] = new Reader (Pricesinf o); threadsreader[i]=new Thread (Reader[i]);} Writer writer = new writer (pricesinfo); Thread threadwriter = new Thread (writer), for (int i = 0; i < threadsreader.length; i++) {Threadsreader[i].start ();} Threadwriter.start ();}}
Java Concurrency Learning 15--Synchronizing data access with read-write locks