加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

JAVA多线程重入锁ReentrantLock应用

发布时间:2020-12-15 05:31:14 所属栏目:Java 来源:网络整理
导读:package concurrent; import java.util.concurrent.*; import java.util.concurrent.locks.ReentrantLock; /** * @Auther:zhl * @Date:2019/7/13 * @Description: 并发测试,重入锁ReentrantLock解决并发问题 */ public class ConcurrentSample { //并发
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(); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读