ExecutorService,Semaphore,CountDownLatchスレッドセキュリティかどうかを測定
1210 ワード
public class StringExample1 {
//
public static int clientTotal = 5000;
//
public static int threadTotal = 200;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
//
update();
semaphore.release();
} catch (Exception e) {
log.error("exception", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
//
log.info("size:{}", stringBuilder.length());
}
private static void update() {
//
stringBuilder.append("1");
}
}