我正在实现一个控制器类,它必须在处理相同类型数据的线程上应用锁。因此,在这种情况下,我构建了两个用于应用和释放锁的类。
现在我在重新锁定时收到 IllegalMonitorStateException 异常。我知道目前我在另一个线程的监视器中。
这是锁定机制:
ConcurrentHashMap<String, Thread> Map = new ConcurrentHashMap<String, Thread>();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
final Object lock = new Object();
for (Thread thread : threadSet) {
StringBuffer sb = new StringBuffer(thread.getName().toString());
if ((sb.length() == 22) && (sb.toString().matches("[0-9]+"))
&& (thread != Thread.currentThread())) {
utiMap.put(thread.getName().toString(), thread);
}
}
synchronized (lock) {
if (utiMap.containsKey(key)) {
try {
lock.wait();
} catch (InterruptedException e) {
lock.notifyAll();
}
}
}
以下是锁释放逻辑。
ConcurrentHashMap<String, Thread> Map = new ConcurrentHashMap<String, Thread>();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Object lock = new Object();
for (Thread thread : threadSet) {
StringBuffer sb = new StringBuffer(thread.getName().toString());
if ((sb.length() == 22) && (sb.toString().matches("[0-9]+"))
&& (thread != Thread.currentThread()) && thread.getState().name().equals("WAITING")) {
utiMap.put(thread.getName().toString(), thread);
System.out.println("I am in controller Release -- ");
thread.resume();
}
}