您好,登錄后才能下訂單哦!
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();
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。