java之读写锁ReadWriteLock

读写锁:核心思想实现读写分离,高并发下特别适合 读多写少的场景。 
因为synchronized关键字和ReentrantLock 同一时间只能有一个线程进行访问被锁定的代码,读写锁的机制则不是,本质上分为两把锁,读锁和写锁,在读锁情况下,多个线程可以并发访问资源,只有当是写锁时只能一个一个的顺序执行。 
口诀:读读共享,写写互斥,读写互斥。

代码如下:

package com.example.demo;

public class Test {

    public static void main(String[] args) {
        final Printer printer = new Printer();

        Thread thread1 = new Thread(){
            @Override
            public void run() {
                printer.read("thread1 read...");
                printer.write("thread1 write...");
            }
        };
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                printer.read("thread2 read...");
                printer.write("thread2 write...");
            }
        };
        thread1.start();
        thread2.start();
    }
}

操作类:
package com.example.demo;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Printer {
    ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 读操作
     * @author stone
     * @date 2018-08-07
     */
    public void read(String str){
        lock.readLock().lock();//读锁1
        try{
            for (int i = 0; i < 3; i++) {
                try {
                    System.out.println(str);
                    Thread.sleep(200);//暂停200ms,不释放锁,以便更好的观察输出结果
                } catch (InterruptedException e) {

                }
            }
        }finally{
            lock.readLock().unlock();//解锁,要放在finnall块里面
        }
    }

    /**
     * 写操作
     * @author stone
     * @date 2018-08-07
     */
    public void write(String str){
        lock.writeLock().lock();//写锁
        try{for (int i = 0; i < 3; i++) {
            try {
                System.out.println(str);
                Thread.sleep(200);//暂停200ms,不释放锁,以便更好的观察输出结果
            } catch (InterruptedException e) {

            }
        }
        }finally{
            lock.writeLock().unlock();//解锁
        }
    }
}

结果如下:
thread1 read...
thread2 read...
thread2 read...
thread1 read...
thread2 read...
thread1 read...
thread1 write...
thread1 write...
thread1 write...
thread2 write...
thread2 write...
thread2 write...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值