我遇到一种情况,我需要实现一个线程安全的方法,该方法一次只能由一个线程执行,当该方法由一个线程执行时,所有其他尝试执行同一方法的线程都应该执行t 等待并且必须退出该方法。
同步在这里没有帮助,因为线程将等待顺序执行该方法。
我想我可以通过使用下面的代码使用 ConcurrentHashMap 来实现这一点,但不确定这是否是实现它的完美方法。
Class Test {
private ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
public void execute() {
if (map.putIfApsent("key", new Object()) != null) { // map has value for key which means a thread has already entered.
return; // early exit
}
threadSafeMethod();
map.remove("key");
}
private void threadSafeMethod() {
// my code
}
}
Run Code Online (Sandbox Code Playgroud) java concurrency multithreading synchronization single-threaded