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(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)