我从一个开源项目中读了一些有趣的代码,但我并没有真正理解它。使用ConcurrentHashMap来模拟锁,是否确定安全?
下面的concurrentMapExample是一个java.util.concurrent.ConcurrentMap。 下面的代码可以防止多个线程同时返回isLocked = true吗?
public boolean tryLock()
{
isLocked = concurrentMapExample.putIfAbsent(key, "") == null;
return isLocked;
}
对我的答案有任何反馈?如果它帮助你,请记得接受它。 – Gray