码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程重入锁ReentrantLock应用

时间:2019-08-01 14:21:35      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:sem   ace   rup   catch   user   read   lease   exec   并发   

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应用

标签:sem   ace   rup   catch   user   read   lease   exec   并发   

原文地址:https://blog.51cto.com/11147669/2425591

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!