当我单击调用线程等待()的停止按钮时,Java GUI停止响应

当我单击调用线程等待()的停止按钮时,Java GUI停止响应,java,multithreading,user-interface,Java,Multithreading,User Interface,当我在GUI上单击stop按钮,通过事件侦听器调用下面的代码时,GUI停止响应。我知道wait()必须同步,但调用它的正确方法是什么?提前谢谢 public void actionPerformed(ActionEvent actionEvent) { if(actionEvent.getSource().equals(ui.stop)) { if(clickerThread != null) { /*terminate(

当我在GUI上单击stop按钮,通过事件侦听器调用下面的代码时,GUI停止响应。我知道wait()必须同步,但调用它的正确方法是什么?提前谢谢

public void actionPerformed(ActionEvent actionEvent) {
        if(actionEvent.getSource().equals(ui.stop)) {
            if(clickerThread != null) {

                /*terminate() stops the while loop 
                running in the thread's run(); */
                autoClicker.terminate();

                synchronized(clickerThread) {
                    try {
                        clickerThread.wait();
                        ui.updateLabel("Idle", ui.state);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
}
以下是创建线程的方式,以防有帮助:

else if(actionEvent.getSource().equals(ui.play)) {
            if(clickerThread == null) {
                autoClicker= new AutoClicker();
                clickerThread = new Thread(autoClicker);
                clickerThread.start();
                ui.updateLabel("playing", ui.state);
            }
}

正如您所发现的,调用
wait()
并不会冻结调用它的线程(事实上,它可以在任何“监视器”对象上调用——不管是不是线程),而是在中调用它的线程。根据(并养成在询问之前阅读API的习惯):

使当前线程等待,直到另一个线程调用此对象的notify()方法或notifyAll()方法

最好为clickerThread类提供一个GUI可以调用的公共方法来暂停和恢复执行。因此,您可能希望为clickerThread类提供一个在决定是否继续运行时检查的
volitile
布尔字段,然后为该类提供一个公共方法来设置该字段的值