Java并发学习之十五——使用读写锁同步数据访问
本文是学习网络上的文章时的总结,感谢大家无私的分享。
读写锁重要的是写锁的使用,只用一个入口。
下面是读写锁使用的例子
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; } @Override public 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; } @Override public void run() { for(int i=0;i<3;i++){ int p1 = new Random().nextInt(47); int p2 = new Random().nextInt(47)*10; System.out.println("Writer:Attempt to modify the prices."+p1+" price2:"+p2); pricesInfo.setPrices(p1, p2); System.out.println("Writer:Prices have 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(pricesInfo); 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(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。