之前我们说过线程安全问题可以用锁机制来解决,即线程必要要先获得锁,之后才能进行其他操作。其实在 Java 的 API 中有这样一些锁类可以提供给我们使用,与其他对象作为锁相比,它们具有更强大的功能。

Java 中的锁有两种,分别是:1)同步锁 2)读写锁

一、同步锁

  同步锁(ReentrantLock)类似于 synchronize 代码块中传入的那个锁对象,可以用于进行线程同步。ReentrantLock.lock() 方法用于锁定对象,而 ReentrantLock.unlock 用于释放锁对象。

public class SynLockDemo {

    static final ReentrantLock lock = new ReentrantLock();   //同步锁

    public static void main(String args[]) {
//线程1
new Thread(){
public void run() {
lock.lock();
System.out.println(Thread.currentThread().getName() + " have the lock.");
try {
System.out.println(Thread.currentThread().getName() + " sleep 3 Seconds.");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
System.out.println(Thread.currentThread().getName() + " release the lock.");
}
}.start();
//线程2
new Thread(){
public void run() {
lock.lock();
System.out.println(Thread.currentThread().getName() + " have the lock.");
lock.unlock();
System.out.println(Thread.currentThread().getName() + " release the lock.");
}
}.start();
}
}

  可以看到线程 1 即使休眠了 3 秒,线程 2 也还是会等到线程 1 执行完才会继续执行。

  ReentrantLock 除了可以实现基本的线程同步阻塞之外,还可以配合 Condition 类使用,实现线程通信。我们可以用 Condition 来实现生产者 - 消费者问题:

public class Test {
    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();
      
    public static void main(String[] args)  {
        Test test = new Test();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();
           
        producer.start();
        consumer.start();
    }
       
    class Consumer extends Thread{
           
        @Override
        public void run() {
            consume();
        }
           
        private void consume() {
            while(true){
                lock.lock();
                try {
                    while(queue.size() == 0){
                        try {
                            System.out.println("队列空,等待数据");
                            notEmpty.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.poll();                //每次移走队首元素
                    notFull.signal();
                    System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                } finally{
                    lock.unlock();
                }
            }
        }
    }
       
    class Producer extends Thread{
           
        @Override
        public void run() {
            produce();
        }
           
        private void produce() {
            while(true){
                lock.lock();
                try {
                    while(queue.size() == queueSize){
                        try {
                            System.out.println("队列满,等待有空余空间");
                            notFull.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.offer(1);        //每次插入一个元素
                    notEmpty.signal();
                    System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                } finally{
                    lock.unlock();
                }
            }
        }
    }
}

二、读写锁

ReentrantReadWriteLock 是 Java 中用于控制读写的一个类。lock.readLock 方法用于获取一个读锁,而 lock.writeLock 方法用于获取一个写锁。读锁允许多个线程进行读取数据操作,但不允许修改操作。而写锁则不允许其他线程进行读和写操作。

我们改写下上面的 Demo,将 ReentrantLock 换成 ReentrantReadWriteLock,并锁上读锁

public class ReadWriteLockDemo {

    static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();   //同步锁

    public static void main(String args[]) {
//线程1
new Thread(){
public void run() {
// rwl.readLock().lock();
rwl.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " have the lock.");
try {
System.out.println(Thread.currentThread().getName() + " sleep 3 Seconds.");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
rwl.writeLock().unlock();
System.out.println(Thread.currentThread().getName() + " release the lock.");
}
}.start();
//线程2
new Thread(){
public void run() {
rwl.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " have the lock.");
rwl.writeLock().unlock();
System.out.println(Thread.currentThread().getName() + " release the lock.");
}
}.start();
}
}

运行结果:

Thread- have the lock.
Thread- sleep Seconds.
Thread- have the lock.
Thread- release the lock.
Thread- release the lock.

从结果可以看出,线程0获取到锁并不会阻塞线程1获取锁,因此可以知道读锁其实是并发的。

如果我们把上面的 rwl.readLock() 换成 rwl.writeLock(),那么线程1就会等到线程0释放锁之后才会继续执行。

三、一个读写锁的例子

读写锁与一般的锁的不同之处就是它有两种锁,分别是读锁(ReadLock)和写锁(WriteLock)。当我们锁上读锁的时候,其他线程也可以读取对象的数据,但是不能修改。但当我们锁上写锁的时候,其他线程就无法进行读操作,也没办法进行写操作。这样就即保证了读取数据的高并发,又保证了线程的数据安全。下面我们来看一个例子:

package com.chanshuyi.class12;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁实现读写互斥又不影响并发读取
* @author chenyr
* @time 2014-12-18 下午09:41:14
* All Rights Reserved.
*/
public class ReadWriteLock1 { public static void main(String args[]){
final MyQueue queue = new MyQueue();
for(int i = 0; i < 3; i++){
new Thread(){
public void run(){
while(true){ //不断读取数据
queue.get();
}
}
}.start(); new Thread(){
public void run(){
while(true){ //不断写入数据
queue.put(new Random().nextInt(10000));
}
}
}.start();
}
} } class MyQueue{
private Object data = null; //共享数据
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); //写
public void put(Object obj){
rwl.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " is ready to write !");
try{
Thread.sleep((long)(Math.random() * 1000)); //因为是不断写入,所以必须让线程休眠,避免CPU耗尽
}catch(Exception e){
e.printStackTrace();
}
this.data = obj;
System.out.println(Thread.currentThread().getName() + " has complte write :" + this.data);
rwl.writeLock().unlock();
try{
Thread.sleep(1000); //让写进程休眠长一点时间,否则会导致读取进程很久都无法读取数据。
}catch(Exception e){
e.printStackTrace();
}
}
//读
public void get(){
rwl.readLock().lock();
System.out.println(Thread.currentThread().getName() + " is ready to read !");
try{
Thread.sleep((long)(Math.random() * 1000)); //因为是不断读取,所以必须让线程休眠,避免CPU耗尽
}catch(Exception e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "has read the value :" + this.data);
rwl.readLock().unlock();
}
}

在上面这个例子中,我们创建了3个读数据进程以及3个写数据进程,不断取出、写入MyQueue中的数据。在MyQueue调用读取数据get()方法时,锁上读锁,在调用写数据put()方法时,锁上写锁。下面是一部分的运行结果:

 1 Thread-1 is ready to read !
2 Thread-3 is ready to read !
3 Thread-5 is ready to read !
4 Thread-1has read the value :null
5 Thread-3has read the value :null
6 Thread-5has read the value :null
7 Thread-6 is ready to write !
8 Thread-6 has complte write :4138
9 Thread-4 is ready to write !
10 Thread-4 has complte write :6158
11 Thread-2 is ready to write !
12 Thread-2 has complte write :3333
13 Thread-1 is ready to read !
14 Thread-5 is ready to read !
15 Thread-3 is ready to read !
16 Thread-3has read the value :3333
17 Thread-3 is ready to read !
18 Thread-5has read the value :3333
19 Thread-5 is ready to read !
20 Thread-1has read the value :3333
21 Thread-1 is ready to read !
22 Thread-3has read the value :3333
23 Thread-1has read the value :3333
24 Thread-5has read the value :3333
25 Thread-6 is ready to write !
26 Thread-6 has complte write :6568
27 Thread-4 is ready to write !
28 Thread-4 has complte write :4189
29 Thread-3 is ready to read !
30 Thread-1 is ready to read !
31 Thread-3has read the value :4189
32 Thread-1has read the value :4189

从上面的运行结果我们可以看到:1-3行,13-15行出现了多个线程同时读取数据的情况。

观察输出结果,可以发现在写入数据的时候(如 7 - 12 行),即使有多次连续写入数据,但是都是等待一个线程写入结束后,另一个线程才开始写入数据的,没有出现同时多个线程写入的情况。这就说明写锁不允许多个线程同时写,也不允许读。

这就是读写锁的一个非常重要的应用,比起synchronized或lock锁,它允许多个线程同时读,但是同时有保证了写数据的时候不会有多个线程同时操作。也就是保证了程序读取的并发性能,又保证了线程的数据安全。

Java并发编程:同步锁、读写锁的更多相关文章

  1. java并发编程-StampedLock高性能读写锁

    目录 一.读写锁 二.悲观读锁 三.乐观读 欢迎关注我的博客,更多精品知识合集 一.读写锁 在我的<java并发编程>上一篇文章中为大家介绍了<ReentrantLock读写锁> ...

  2. Java并发编程笔记之读写锁 ReentrantReadWriteLock 源码分析

    我们知道在解决线程安全问题上使用 ReentrantLock 就可以,但是 ReentrantLock 是独占锁,同时只有一个线程可以获取该锁,而实际情况下会有写少读多的场景,显然 Reentrant ...

  3. Java并发编程:锁的释放

    Java并发编程:锁的释放 */--> code {color: #FF0000} pre.src {background-color: #002b36; color: #839496;} Ja ...

  4. 多线程高并发编程(4) -- ReentrantReadWriteLock读写锁源码分析

    背景: ReentrantReadWriteLock把锁进行了细化,分为了写锁和读锁,即独占锁和共享锁.独占锁即当前所有线程只有一个可以成功获取到锁对资源进行修改操作,共享锁是可以一起对资源信息进行查 ...

  5. Java并发编程之锁机制

    锁分类 悲观锁与乐观锁 悲观锁认为对于同一个数据的并发操作,一定是会发生修改的,哪怕没有修改,也会认为修改.因此对于同一个数据的并发操作,悲观锁采取加锁的形式.悲观的认为,不加锁的并发操作一定会出问题 ...

  6. Java并发编程-各种锁

    安全性和活跃度通常相互牵制.我们使用锁来保证线程安全,但是滥用锁可能引起锁顺序死锁.类似地,我们使用线程池和信号量来约束资源的使用, 但是缺不能知晓哪些管辖范围内的活动可能形成的资源死锁.Java应用 ...

  7. Java并发(8)- 读写锁中的性能之王:StampedLock

    在上一篇<你真的懂ReentrantReadWriteLock吗?>中我给大家留了一个引子,一个更高效同时可以避免写饥饿的读写锁---StampedLock.StampedLock实现了不 ...

  8. java并发编程:锁的相关概念介绍

    理解同步,最好先把java中锁相关的概念弄清楚,有助于我们更好的去理解.学习同步.java语言中与锁有关的几个概念主要是:可重入锁.读写锁.可中断锁.公平锁 一.可重入锁 synchronized和R ...

  9. JAVA并发,同步锁性能测试

    测试主要从运行时间差来体现,数据量越大,时间差越明显,例子如下: package com.xt.thinks21_2; /** * 同步锁性能测试 * * @author Administrator ...

  10. Java并发编程的艺术读后总结

    2019.04.26 - 2019.04.28扫了一遍 Chapter volatile synchronized实现原理 Java内存模型 happen-before 重排序 顺序一致性 JMM 线 ...

随机推荐

  1. ant编译java的例子

    ant hello world 建一上文件夹HelloWorld.里面的内容如下所示: 第一个例子不讨论build1.xml和HelloWorld1.java.运行出helloworld程序要如下步骤 ...

  2. 深度了解Android 7.0 ,你准备好了吗?

    作者:Redyan, 腾讯移动客户端开发工程师 商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. 原文链接:http://wetest.qq.com/lab/view/288.html ...

  3. 新学到的xss姿势,分享一下

    在js中有一种神奇的对象叫做window 当页面中包含如类似的 <script>var c = urlQuery("callback"); var r = JSON.p ...

  4. unity3d为什么会有三种脚本语言?

    相信这个问题多多少少会令许多初学者感到困惑,因为他们不知道应该选择哪种语言好,但是都会从以下几个方面进行考虑: 1.学习成本.哪门语言让我快速上手. 2.文档帮助.说白了就是出了问题,有没有人能解决. ...

  5. 【转】Netty系列之Netty并发编程分析

    http://www.infoq.com/cn/articles/netty-concurrent-programming-analysis

  6. HTTP基础知识(一)

    一.了解web及网络基础 1.通过发送请求获取服务器资源的web浏览器等的都可称为客户端(client) 2.HTTP:HyperText Transfer Protocol,超文本传输协议:所有的W ...

  7. SQL SERVER 事务日志 解析

    1 基本介绍 每个数据库都具有事务日志,用于记录所有事物以及每个事物对数据库所作的操作. 日志的记录形式需要根据数据库的恢复模式来确定,数据库恢复模式有三种: 完整模式,完全记录事物日志,需要定期进行 ...

  8. Java设计模式之《组合模式》及应用场景

    摘要: 原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6489827.html 组合模式,就是在一个对象中包含其他对象,这些被包含的对象可能是 ...

  9. 浅谈Linux下如何修改IP

    linux 下命令之浅谈//cd ..  //返回上一级//创建文件夹touch test.txt//Linux不区分大小写//往一个文件中追加内容echo "****" > ...

  10. npm学习总结

    1.npm run [scripts name]的作用及意义: npm 局部安装的工具包不能像全局安装那样直接执行命令行,但可写成命令行执行语句,通过npm run来运行,该命令可将node_modu ...