gpt4 book ai didi

java - 为什么我的循环仅在使用 SOUT 时继续?

转载 作者:行者123 更新时间:2023-12-02 02:50:06 25 4
gpt4 key购买 nike

所以我有一个相当大的项目,但最终将问题归结为以下情况。

我有主类“LoopTest”和另一个类“RandomClassObject”

循环测试:

public class LoopTest {

static RandomClassObject rco;
public static void main(String[] args) {
rco = new RandomClassObject();
System.out.println("RCO has finished");
}

}

随机类对象:

public class RandomClassObject {

JFrame frame = new JFrame();
JButton button = new JButton("Click Me");
boolean created = false;

public RandomClassObject() {
button.addActionListener(this::buttonActionPerformed);
frame.add(button);
frame.setVisible(true);
while (!created) {
//System.out.println("Done"); //This needs to be uncommented to work.
}
System.out.println("It was been Created");
}

public void buttonActionPerformed(ActionEvent evt) {
created = true;
}

所以我希望我的 RandomClassObject 等待直到按下按钮。我有一个“创建”的 boolean 值,并且有一个 while 循环,该循环会一直循环,直到所述 boolean 值更改为 true。

在注释掉 SOUT“完成”的情况下运行时,我单击按钮,但从未获得第二个 SOUT“已创建”。

在未注释 SOUT“完成”的情况下运行时,我会收到“完成”的垃圾邮件,一旦单击按钮,我就会收到 SOUT“已创建”。

我需要帮助理解为什么我必须在 While 循环中放置 SOUT,以便循环在单击按钮时退出。

很抱歉,如果这是一个明显的错误,感谢您的回复!

最佳答案

您遇到同步问题。按钮单击发生在事件线程中,并且您的循环(在主线程中运行)永远看不到它所做的更新。因为您不强制两个线程之间的内存同步,所以机器可以自由地忽略更改。

对 System.out.println 的调用具有强制内存同步的副作用,允许主线程看到事件线程所做的更改。

要解决此问题,请将 created 设置为 AtomicBoolean 或将 synchronized 关键字添加到您的 complete 方法中。

无论如何,循环都是实现此结果的糟糕方法。考虑从按钮上的事件监听器驱动完成逻辑。

您说您需要暂停主线程,直到创建角色。一种方法是使用闩锁:

public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);

JFrame frame = new JFrame("Test...");
JButton button = new JButton("Click Me");
button.addActionListener(e -> latch.countDown());
frame.add(button);
frame.pack();
frame.setVisible(true);

// Wait here for the click in the event thread
latch.await();

System.out.println("Clicked!");

frame.dispose();
}
}

调用 latch.await() 将阻塞您的主线程,直到您的事件线程使用 latch.countDown() 释放闩锁。

关于java - 为什么我的循环仅在使用 SOUT 时继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43990766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com