锁机制带来的最有意义的改进是提供了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. 使用JavaStream将List转为Map

    有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top 首发博客地址 系列文章地址 使用Java Stream将List转换为Map ...

  2. [转帖]ipv6相关内核参数配置的优化实践

    https://zhuanlan.zhihu.com/p/605217713 调整ARP缓存大小 这个参数通常需要在高负载的访问服务器上增加.比如繁忙的网络(或网关/防火墙 Linux 服务器),再比 ...

  3. TiDB的搭建与维护过程

    TiDB的搭建与维护过程 背景 总结一下TiDB的搭建以及简单维护过程. 目标: 简单快速的创建TiDB数据库,以及进行备份恢复等工作. TiDB 简介 TiDB(全称:Ti Distributed ...

  4. 人工智能GPT科普知识的简单总结

    人工智能GPT相关知识的简单总结 背景 工作已经很久, 工作十几年来有过好多波新的技术浪潮. 但是每次都离技术前沿比较远. 最近发现只低头拉车是一个没有前途的行为. 人生很短, 选择很重要, 不仅要低 ...

  5. [转帖]linux,wget 的证书不可信,证书使用不安全的算法签名

    centos wget 的证书不可信,证书使用不安全的算法签名 wget wget https://www.php.net/distributions/php-7.4.28.tar.gz 出现错误: ...

  6. 在线获取所有依赖rpm包的方法

    背景 现在经常有一些不能上网的LInux机器但是需要安装一些软件. 但是有时候经常因为有依赖关系找不到的情况比较麻烦. 或者是一些公司的网络总是受限,网络速度非常慢. 下载安装非常折磨人. 这个时候就 ...

  7. vite构建打包产物

    构建打包产物 build: { assetsInlineLimit: 10240, //静态资源(不会包含js,css)不超过10kb 转化为 base64 [不好含css js] outDir: & ...

  8. P5963 [BalticOI ?] Card 卡牌游戏【来源请求】

    [rt](https://www.luogu.com.cn/problem/P5963)------------## part1### 题意简述给你 $n$ 张纸牌,每张纸牌有两个面.将 $n$ 张纸 ...

  9. python2和python3的版本历史及入门书籍

    python版本历史 我们端游项目使用是python2.7版本 32位 python2 2.7.18 last version on 2020.4.20 2.7 first version on 20 ...

  10. SqlSugar删除数据

    1.根据实体删除 1.1 强类型实体 需要配置主键 ,根据主键删除需要给实体配置主键,参考文档实体配置 //单个实体 db.Deleteable<Student>(new Student( ...