java多线程之ReadWriteLock

java多线程之ReadWriteLock,第1张

java多线程之ReadWriteLock 简介

ReadWriteLock是一个读写互斥、读读不互斥的锁。ReadWriteLock是一个接口,内部有两个方法readLock和writeLock,一个是读锁,一个是写锁。ReetrantReadWriteLock实现了ReadWriteLock接口,添加了可重入性并支持公平与非公平模式。ReadWriteLock支持锁降级就是从写锁变成读锁,不支持锁升级就是从读锁变成写锁

例子
package com.test.juc.lock;

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

public class TestReadWriteLock {

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    static Lock readLock = readWriteLock.readLock();

    static Lock writeLock = readWriteLock.writeLock();

    private static void read(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("read");
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static void write(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("write");
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Runnable read = () -> read(readLock);
        Runnable write = () -> write(writeLock);
        for(int i = 0; i < 4; i++) {
            new Thread(read).start();
        }

        for(int i = 0; i < 3; i++) {
            new Thread(write).start();
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5161830.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存