【详解】JUC之读写锁

引出

读写锁的设计主要参考读写锁的设计模式:https://blog.csdn.net/qq_43040688/article/details/105857920

使用

public class ReadWriteLockTest {

    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

    private static final Lock readLock = lock.readLock();
    private static final Lock writeLock = lock.writeLock();

    private static final List<Long> data = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->write(),"write-1").start();

        Thread.sleep(1000);
        new Thread(()->read(),"read-1").start();

        new Thread(()->read(),"read-2").start();

    }

    public static void write(){
        try{
            writeLock.lock();
            data.add(System.currentTimeMillis());
                Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void read(){
        try{
            readLock.lock();
            for (Long datum : data) {
                System.out.println(datum);
            }
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + "************************");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }
}
全部评论

相关推荐

10-25 23:12
门头沟学院 Java
点赞 评论 收藏
分享
11-26 22:34
已编辑
重庆邮电大学 Java
快手 客户端开发 (n+5)k*16 公积金12
牛客895077908号:佬 什么双非硕啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务