锁机制带来的最有意义的改进是提供了ReadWriteLock接口及其实现类ReentrantReadWriteLock。

这个类有2个锁,一个针对读操作另一个针对写操作。

可以有多个线程使用读操作,但是只有一个线程使用写操作。

当一个线程做写操作时,不能有任何线程做读操作。

本例中,我们将学习如何通过ReadWriteLock接口实现一个对2个产品价格的访问进行控制。

PricesInfo.java
package com.dylan.thread.ch2.c05.task;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; /**
* This class simulates the store of two prices. We will
* have a writer that stores the prices and readers that
* consult this prices
*
*/
public class PricesInfo { /**
* The two prices
*/
private double price1;
private double price2; /**
* Lock to control the access to the prices
*/
private ReadWriteLock lock; /**
* Constructor of the class. Initializes the prices and the Lock
*/
public PricesInfo(){
price1=1.0;
price2=2.0;
lock=new ReentrantReadWriteLock();
} /**
* Returns the first price
* @return the first price
*/
public double getPrice1() {
lock.readLock().lock();
double value=price1;
lock.readLock().unlock();
return value;
} /**
* Returns the second price
* @return the second price
*/
public double getPrice2() {
lock.readLock().lock();
double value=price2;
lock.readLock().unlock();
return value;
} /**
* Establish the prices
* @param price1 The price of the first product
* @param price2 The price of the second product
*/
public void setPrices(double price1, double price2) {
lock.writeLock().lock();
this.price1=price1;
this.price2=price2;
lock.writeLock().unlock();
}
}
Reader.java
package com.dylan.thread.ch2.c05.task;

/**
* This class implements a reader that consults the prices
*
*/
public class Reader implements Runnable { /**
* Class that stores the prices
*/
private PricesInfo pricesInfo; /**
* Constructor of the class
* @param pricesInfo object that stores the prices
*/
public Reader (PricesInfo pricesInfo){
this.pricesInfo=pricesInfo;
} /**
* Core method of the reader. Consults the two prices and prints them
* to the console
*/
@Override
public void run() {
for (int i=0; i<10; i++){
System.out.printf("%s: Price 1: %f\n",Thread.currentThread().getName(),pricesInfo.getPrice1());
System.out.printf("%s: Price 2: %f\n",Thread.currentThread().getName(),pricesInfo.getPrice2());
}
} }
Writer.java
package com.dylan.thread.ch2.c05.task;

/**
* This class implements a writer that establish the prices
*
*/
public class Writer implements Runnable { /**
* Class that stores the prices
*/
private PricesInfo pricesInfo; /**
* Constructor of the class
* @param pricesInfo object that stores the prices
*/
public Writer(PricesInfo pricesInfo){
this.pricesInfo=pricesInfo;
} /**
* Core method of the writer. Establish the prices
*/
@Override
public void run() {
for (int i=0; i<3; i++) {
System.out.printf("Writer: Attempt to modify the prices.\n");
pricesInfo.setPrices(Math.random()*10, Math.random()*8);
System.out.printf("Writer: Prices have been modified.\n");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} }
Main.java
package com.dylan.thread.ch2.c05.core;

import com.dylan.thread.ch2.c05.task.PricesInfo;
import com.dylan.thread.ch2.c05.task.Reader;
import com.dylan.thread.ch2.c05.task.Writer; /**
* Main class of the example
*
*/
public class Main { /**
* Main class of the example
* @param args
*/
public static void main(String[] args) { // Creates an object to store the prices
PricesInfo pricesInfo=new PricesInfo(); Reader readers[]=new Reader[5];
Thread threadsReader[]=new Thread[5]; // Creates five readers and threads to run them
for (int i=0; i<5; i++){
readers[i]=new Reader(pricesInfo);
threadsReader[i]=new Thread(readers[i]);
} // Creates a writer and a thread to run it
Writer writer=new Writer(pricesInfo);
Thread threadWriter=new Thread(writer); // Starts the threads
for (int i=0; i<5; i++){
threadsReader[i].start();
}
threadWriter.start(); } }

运行结果:

Thread-0: Price 1: 1.000000
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 2.000000
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 2.000000
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 2.000000
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 2.000000
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 2.000000
Writer: Attempt to modify the prices.
Thread-3: Price 1: 1.000000
Thread-3: Price 2: 1.280423
Thread-3: Price 1: 3.047936

...

Java并发编程实例--17.使用read/write锁同步数据访问的更多相关文章

  1. Java并发编程原理与实战十一:锁重入&自旋锁&死锁

    一.锁重入 package com.roocon.thread.t6; public class Demo { /* 当第一个线程A拿到当前实例锁后,进入a方法,那么,线程A还能拿到被当前实例所加锁的 ...

  2. 【Java并发编程实战】----- AQS(四):CLH同步队列

    在[Java并发编程实战]-–"J.U.C":CLH队列锁提过,AQS里面的CLH队列是CLH同步锁的一种变形.其主要从两方面进行了改造:节点的结构与节点等待机制.在结构上引入了头 ...

  3. java并发编程的艺术(一)---锁的基本属性

    本文来源于翁舒航的博客,点击即可跳转原文观看!!!(被转载或者拷贝走的内容可能缺失图片.视频等原文的内容) 若网站将链接屏蔽,可直接拷贝原文链接到地址栏跳转观看,原文链接:https://www.cn ...

  4. 【Java并发编程实战】—– AQS(四):CLH同步队列

    在[Java并发编程实战]-–"J.U.C":CLH队列锁提过,AQS里面的CLH队列是CLH同步锁的一种变形. 其主要从双方面进行了改造:节点的结构与节点等待机制.在结构上引入了 ...

  5. Java并发编程实战.笔记十一(非阻塞同步机制)

    关于非阻塞算法CAS. 比较并交换CAS:CAS包含了3个操作数---需要读写的内存位置V,进行比较的值A和拟写入的新值B.当且仅当V的值等于A时,CAS才会通过原子的方式用新值B来更新V的值,否则不 ...

  6. java并发编程JUC第九篇:CountDownLatch线程同步

    在之前的文章中已经为大家介绍了java并发编程的工具:BlockingQueue接口.ArrayBlockingQueue.DelayQueue.LinkedBlockingQueue.Priorit ...

  7. Java并发编程实例(synchronized)

    此处用一个小程序来说明一下,逻辑是一个计数器(int i):主要的逻辑功能是,如果同步监视了资源i,则不输出i的值,但如果没有添加关键字synchronized,因为是两个线程并发执行,所以会输出i的 ...

  8. java并发编程实战《三》互斥锁(上)

    互斥锁(上):解决原子性问题 原子性问题的源头是线程切换,操作系统做线程切换是依赖 CPU 中断的,所以禁止 CPU 发生中断就能够禁止线程切换. 在早期单核 CPU 时代,这个方案的确是可行的,而且 ...

  9. Java并发编程实战(3)- 互斥锁

    我们在这篇文章中主要讨论如何使用互斥锁来解决并发编程中的原子性问题. 目录 概述 互斥锁模型 互斥锁简易模型 互斥锁改进模型 Java世界中的互斥锁 synchronized中的锁和锁对象 synch ...

  10. Java并发编程学习:线程安全与锁优化

    本文参考<深入理解java虚拟机第二版> 一.什么是线程安全? 这里我借<Java Concurrency In Practice>里面的话:当多个线程访问一个对象,如果不考虑 ...

随机推荐

  1. [转帖]AMD处理器ZEN一代之国产化海光

    https://huataihuang.gitbook.io/cloud-atlas-draft/os/linux/kernel/cpu/amd_hygon   2020年国产化处理器受到了广泛的关注 ...

  2. rclone 的下载地址-官方网站

    Downloads Rclone is single executable (rclone, or rclone.exe on Windows) that you can simply downloa ...

  3. SPECJVM2008的简单结果

    SPECJVM2008的简单结果 摘要 前面两天学习了SPECJVM2008简单使用. 今天进行一下简单的数据采集. 需要说明一下SPECJVM2008貌似仅兼容JDK1.8 更新的LTS版本都不兼容 ...

  4. [转帖]OutOfMemoryError内存溢出相关的JVM参数

    原文在这里: OutOfMemoryError内存溢出相关的JVM参数 JVM提供了很多处理内存溢出的相关参数,本文主要来讲解下这些参数,当你遇到内存溢出的时候可能会对你非常有帮助,这些参数主要有: ...

  5. [转帖]计算机体系结构-cache高速缓存

    https://zhuanlan.zhihu.com/p/482651908 本文主要介绍了cache的基本常识.基本组成方式.写入方法和替换策略,在基本组成方式和替换策略两节给出了较为详细的硬件实现 ...

  6. [转]流程自动化机器人(RPA)概念、原理与实践

    [转]流程自动化机器人(RPA)概念.原理与实践 http://blog.sina.com.cn/s/blog_be0833d00102yho9.html 大多数人每天都会使用到一些机器人流程自动化工 ...

  7. 银河麒麟安装LLDB的方法以及调试 dump 文件 (未完成)

    今天同事要进行 lldb进行调试dotnet的bug 本来在x86 上面进行相应的处理 但是发现报错. 没办法 正好有一台借来的arm服务器就搞了一下. 简单记录一下安装方法 1. 安装 apt的so ...

  8. void的讲解 、any的讲解 、联合类型的讲解

    1. void的使用 空值一般采用 void 来表示,同时void也可以表示变量 也可以表示函数没有返回值哈 使用了 void 就不能够使用 return 哈 let sum = function() ...

  9. elementui出现展开后子菜单宽度多出1px问题

    添加 就可以解决了 .el-menu { border-right-width: 0; } <template> <div class="compen-left-men&q ...

  10. 基于go-restful实现的PoW算力池模型

    最开始知道区块链是在17年初,当时因为项目压力不大,开始研究比特币源码.对于比特币中提到的Proof of Work,当时只是一眼带过,并没有详细查看过相关的代码.在最近的项目中,考虑到性能的要求,需 ...