我正在尝试在我的应用程序中同步不同的线程。基本上有一些线程应该能够阻止应用程序关闭。这是我所拥有的:
public class Test{
public static void main(String args[]){
Syncer syncer = new Syncer();
Object o = new Object();
syncer.lockExit(o);
//.. do some stuff//
syncer.unlockExit(o);
}
}
public class Syncer {
private List<Object> l_Exit;
public Syncer() {
l_Exit = new ArrayList<Object>();
}
public synchronized void lockExit(Object o) {
l_Exit.add(o);
}
public synchronized void unlockExit(Object o) {
l_Exit.remove(o);
if (l_Exit.isEmpty()) {
l_Exit.notifyAll();
}
}
public synchronized void waitForExit() {
while (!l_Exit.isEmpty()) {
try {
l_Exit.wait();
} catch (InterruptedException ex) {
Test.log.log(Level.SEVERE, null, ex);
}
}
}
}
运行 syncer.unlockExit(o); 时出现 IllegalMonitorException;