本文是学习网络上的文章时的总结。感谢大家无私的分享。
读写锁重要的是写锁的使用,仅仅用一个入口。
以下是读写锁使用的样例
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(); } }