Use Set to save the id of the Thread that has called this method. When entering the method, first determine whether the id of the current thread is already included in the Set:
private final Set<Long> THREADS = new HashSet<>();
public void someMethod () {
if (THREADS.contains(Thread.currentThread().getId())) {
throw new RuntimeException("该线程不能再调用这个方法");
}
THREADS.add(Thread.currentThread().getId());
// 方法内容
}
Use Set to save the id of the Thread that has called this method. When entering the method, first determine whether the id of the current thread is already included in the Set:
Thread.getCurrentThread.getId()
Customize a Thread class
Add a boolean member to the customized Thread for judgment
Example
public class Main
{
public static void main(String[] args)
}
Run results
Method test invoked!
Others
You can also use ThreadLocal to solve it