资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

JAVA多线程重入锁ReentrantLock应用

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();
    }
}

网站标题:JAVA多线程重入锁ReentrantLock应用
网站网址:http://cdkjz.cn/article/pogcoo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220