简体   繁体   English

在继续使用Java中的另一个线程之前,如何等待线程做某事?

[英]How to wait for a thread to do something before continuing on another thread in Java?

I have a graphical user interface named Welcome, created with JFormDesigner. 我有一个用JFormDesigner创建的名为Welcome的图形用户界面。 I want to wait until a button is clicked on that form before continuing my application. 我要等到在该表单上单击一个按钮后才能继续我的申请。

I am doing this using synchronized and instancing the GUI as the object to wait for. 我正在使用synchronized并实例化GUI作为对象来执行此操作。

synchronized(new Welcome()) {
    wait();
}

Inside of my GUI, I have a start button which when clicked runs this: 在我的GUI内,有一个开始按钮,单击该按钮可运行以下命令:

public void startScript() {
    synchronized(this) {
        notify();
    }

    // Close the GUI
    dispose();
}

The GUI successfully loads however, I get this error: GUI成功加载,但是,出现此错误:

Exception in thread "main" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:502) at dtohh.main.Main.(Main.java:20) at dtohh.tests.Tests.main(Tests.java:11) 线程“ main”中的异常java.lang.Object.wait(本机方法)处的java.lang.IllegalMonitorStateException dtohh.main.Main。(Main.java:处的java.lang.Object.wait(Object.java:502)处的异常20)在dtohh.tests.Tests.main(Tests.java:11)

before I can even press the Start button on my GUI. 我什至无法按一下GUI上的“开始”按钮。 When I then press the button, the script ends and does nothing more. 然后,当我按下按钮时,脚本结束,仅此而已。

I added this to test if it was working correctly: 我添加了此代码以测试其是否正常运行:

synchronized(new Welcome()) {
    wait();
}

System.out.println("Test");

But after the button is pressed, the application exits and the output is not shown. 但是在按下按钮后,应用程序退出,并且不显示输出。 How can I wait for the button to be pressed correctly? 如何等待按钮被正确按下?

I managed to figure it out, I need to wait on the Welcome.class instance and notify using this on the second thread. 我设法弄清楚了,我需要等待Welcome.class实例,并在第二个线程上使用this进行通知。

Main thread: 主线程:

Welcome gui = new Welcome();
syncronized(gui) { gui.wait(); }

Second thread: 第二个线程:

private void onStart() {
    syncronized(this) { notifyAll(); }
    dispose();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM