废话不多讲,直接贴代码:
@Test
public void test02() {
try {
log.debug("开始测试");
ConcurrentMap<String, String> map = CacheBuilder.newBuilder()
.initialCapacity(10)
.expireAfterAccess(1, TimeUnit.HOURS)
.<String, String>build()
.asMap();
CountDownLatch testMainCountDownLatch = new CountDownLatch(1);
int count = 100;
ExecutorService executorService = Executors.newFixedThreadPool(count);
CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
log.debug("{}线程开始了", Thread.currentThread().getName());
Thread.sleep(1000);
countDownLatch.await();
if (StringUtils.isBlank(map.get("hello"))) {
log.debug("{}线程没有读取到值,开始写值", Thread.currentThread().getName());
map.put("hello", Thread.currentThread().getName());
} else {
log.debug("{}线程读取到值:{}", Thread.currentThread().getName(), map.get("hello"));
}
} catch (InterruptedException e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
countDownLatch.countDown();
}
testMainCountDownLatch.await();
} catch (InterruptedException e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
输出存在多个线程向concurrentMap中写值。
我理解应该只有一个线程向concurrentmap中写值。