首页 > 其他分享 >重入锁ReentrantLock

重入锁ReentrantLock

时间:2022-10-12 20:34:27浏览次数:46  
标签:重入 int lock ReentrantLock finally static public

1.重入锁和synchronized比较

特征 synchronized reentrantLock
底层原理 JVM实现 JDK实现
性能区别 低->高(JDK5+)
锁的释放 自动释放(编译器保证) 手动释放(finally保证)
编码程度 简单 复杂
锁的粒度 读写不区分 读锁、写锁
高级功能

公平锁、非公平锁唤醒

Condition分组唤醒

中断等待锁

2.代码

    public static int users = 100;
    public static int downTotal = 50000;
    public static int count = 0;
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(users);
        for (int i = 0; i < downTotal; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        add();
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("下载总数为:"+count);

    }

    private static void add() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();//一定要放在finally中,防止死锁
        }
    }

 

标签:重入,int,lock,ReentrantLock,finally,static,public
From: https://www.cnblogs.com/blanset/p/16785852.html

相关文章