beizili

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

目录

1、什么是读写锁?

2、为什么使用读写锁?

3、怎么使用读写锁?


1、什么是读写锁?

读写锁有很多,最终极的父类就是ReadWriteLock,他把锁分为两类,读锁和写锁。即获得读锁的线程,拥有读取变量的权利;获得写锁的人,拥有写入变量的权利。

2、为什么使用读写锁?

我们都知道java多线程的应用中,不缺乏锁的使用,最经常使用的就是同步锁(synchronized),它的效果是锁住一块逻辑,不管你是 读取 还是 写入,都必须获得锁。

而读写锁的优势就是在把锁分为读和写,使读写操作可以分开控制。例如,读取的操作就可以多个线程同时读取,已提高效率。

3、怎么使用读写锁?

使用方:

  • 读取和写入之前需要获取相应的锁

控制方:

  • 记得需要在finally里面释放锁

下面一个例子,使用Thread.sleep(5000);让读取操作需要耗费5s左右,多(5)个线程同时去读取。如果是同步锁,需要耗费15s以上的时间,但是使用读写锁,只需要5s左右。

package com.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ThreadTest {

    private static ReentrantLock reentrantLock = new ReentrantLock();

    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    private static ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock();

    private static ReentrantReadWriteLock.ReadLock readLock = new ReentrantReadWriteLock().readLock();

    private static String roleItem;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        writeRole("test");
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    System.out.println("roleItem:" + readRole());
                    long ennTime = System.currentTimeMillis();
                    System.out.println("thread:" + Thread.currentThread().getName()+" time:" + (ennTime - startTime));
                }
            });
        }
        executorService.shutdown();
    }

    private static void writeRole(String role) {
        writeLock.lock();
        try {
            roleItem = role;
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            writeLock.unlock();
        }
    }

    private static String readRole() {
        String result = "";
        readLock.lock();
        try {
            result = roleItem;
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            readLock.unlock();
        }
        return result;
    }
}

执行结果:

roleItem:test
thread:pool-1-thread-2 time:5008
roleItem:test
thread:pool-1-thread-4 time:5025
roleItem:test
thread:pool-1-thread-3 time:5023
roleItem:test
thread:pool-1-thread-1 time:5123
roleItem:test
thread:pool-1-thread-5 time:5122

 

更多内容请关注微信公众号“外里科技

官方公众号外里科技
运营公众号英雄赚
微信wxid_8awklmbh1fzm22
QQ1247408032
开源代码https://gitee.com/B_T/beimi

 

posted on 2020-03-30 01:04  被子里  阅读(16)  评论(0)    收藏  举报  来源