JAVA多线程重入锁ReentrantLock应用

发布时间:2020-05-31 17:10:54 作者:恋上程序员
来源:网络 阅读:248
package concurrent;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther:zhl
 * @Date:2019/7/13
 * @Description: 并发测试,重入锁ReentrantLock解决并发问题
 */
public class ConcurrentSample {
    //并发线程数量
    private static int users = 100;
    //访问次数
    private static int count = 10000;
    //访问总量
    private static int number = 0;
    //private static CyclicBarrier cyclicBarrier = new CyclicBarrier(10000);
    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        //定义线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //并发量
        //Semaphore semaphore = new Semaphore(users);
        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            executorService.execute(() -> {
                try {
                    //semaphore.acquire();
                    add();
                    countDownLatch.countDown();
                    //semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("计数器:" + number);
    }

    public static void add() {
        //加锁
        reentrantLock.lock();
        number++;
        //解锁
        reentrantLock.unlock();
    }
}
推荐阅读:
  1. java高并发系列 - 第12天JUC:ReentrantLock重入锁
  2. ReentrantLock (重入锁) 源码浅析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

reentrantlock 重入锁 ava

上一篇:PHP、MySQL和JavaScript学习手册笔记(一)

下一篇:33面向对象8_descriptors

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》