[英]Java concurrency. Block application from exiting
I am trying to synchronize different threads in my application. 我正在尝试同步应用程序中的不同线程。 Basically there are some threads that should be able to block the application from closing.
基本上,有一些线程应该能够阻止应用程序关闭。 Here is what I have:
这是我所拥有的:
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);
}
}
}
}
I get IllegalMonitorException when running syncer.unlockExit(o); 运行syncer.unlockExit(o)时出现IllegalMonitorException。
public synchronized void unlockExit(Object o) {
l_Exit.remove(o);
if (l_Exit.isEmpty()) {
l_Exit.notifyAll();
}
}
You need to be in a synchronized block in order for Object.wait(), Object.notify() or Object.notifyAll() to work. 为了使Object.wait(),Object.notify()或Object.notifyAll()工作,您需要处于同步块中。
public synchronized void unlockExit(Object o) {
synchronized (lock) {
l_Exit.remove(o);
if (l_Exit.isEmpty()) {
l_Exit.notifyAll();
}
}
}
See this question for clarification so as to why. 请参阅此问题进行澄清,以了解原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.