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://m.jcarcd.cn/article/pogcoo.html