java.lang.Object.notify 线程 "AWT-EventQueue-0" java.lang.IllegalMonitorStateException 中的异常(本机方法)
Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method)
我想做什么:
启动window请求参数
我尝试过的:
- 如果我删除
vp.wait()
,window 就会消失。
- 如果我删除
notify()
,程序不会等待。
这是我的代码:
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();
问题来了,在 actionPerformed
.
notify();
您在没有 synchronized
块的情况下执行此操作,因此线程不拥有 this
的监视器...因此出现异常。
但是,您 不只是 想要一个 synchronized
块,因为您实际上是在错误的对象上调用 notify()
。您要使用 ParamsWind
:
synchronized(ParamsWind.this) {
ParamsWind.this.notify();
}
我不清楚使用 wait()
和 notify()
是否真的是您想要的 - 或者您不会以竞争条件结束 - 但那些是 立即 与你正在做的事情有关的问题。
我想做什么:
启动window请求参数
我尝试过的:
- 如果我删除
vp.wait()
,window 就会消失。 - 如果我删除
notify()
,程序不会等待。
这是我的代码:
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();
问题来了,在 actionPerformed
.
notify();
您在没有 synchronized
块的情况下执行此操作,因此线程不拥有 this
的监视器...因此出现异常。
但是,您 不只是 想要一个 synchronized
块,因为您实际上是在错误的对象上调用 notify()
。您要使用 ParamsWind
:
synchronized(ParamsWind.this) {
ParamsWind.this.notify();
}
我不清楚使用 wait()
和 notify()
是否真的是您想要的 - 或者您不会以竞争条件结束 - 但那些是 立即 与你正在做的事情有关的问题。