[英]Exception in thread “AWT-EventQueue-0” java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method)
What I'm trying to do: 我正在尝试做的是:
Launch a window to request parameters 启动一个窗口以请求参数
What I've tried: 我尝试过的
vp.wait()
, the window disappears. 如果删除vp.wait()
,则窗口消失。 notify()
, the program doesn`t wait. 如果我删除notify()
,则程序不会等待。 Here's my code: 这是我的代码:
public static void main(String[] args) throws InterruptedException{
if(args.length==0){
ParamsWind vp = new ParamsWind();
vp.setVisible(true);
synchronized (vp){
try {
vp.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
.....
public class ParamsWind extends JDialog {
...
public ParamsWind()
....
//Create Ok Button and program Action Listener
Button ok = new Button("OK");
...
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(f.getText().equals("") || r.getText().equals("")){
ErrorWind verr = new ErrorWind();
verr.setVisible(true);
}
notify();
Well here's the problem, in actionPerformed
. 好吧,这就是actionPerformed
的问题。
notify();
You're doing that without a synchronized
block, so the thread doesn't own the monitor for this
... hence the exception. 您是在没有synchronized
块的情况下执行此操作的,因此线程不this
拥有监视器...因此是例外。
However, you don't just want a synchronized
block, because you're actually calling notify()
on the wrong object. 但是,您不只是想要一个synchronized
块,因为您实际上是在错误的对象上调用notify()
。 You want to use the ParamsWind
: 您想使用ParamsWind
:
synchronized(ParamsWind.this) {
ParamsWind.this.notify();
}
It's not clear to me that using wait()
and notify()
is really what you want here - or that you won't end up with a race condition - but those are the immediate problems with what you're doing. 对我来说,尚不清楚使用wait()
和notify()
确实是您想要的-否则您将不会遇到竞争状况-但这是您正在做的直接问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.