如果没有正文,Java中的while循环不会检查它们的条件吗?

前端之家收集整理的这篇文章主要介绍了如果没有正文,Java中的while循环不会检查它们的条件吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这个例子中,我有一个简单的JFrame包含一个绑定了ActionListener的JButton.这个AcitonListener只是更改了一个允许程序完成的布尔标志.
  1. public class Test {
  2. public static void main(String[] args){
  3. final boolean[] flag = new boolean[1];
  4. flag[0] = false;
  5. JFrame myFrame = new JFrame("Test");
  6. JButton myButton = new JButton("Click Me!");
  7. myButton.addActionListener(new ActionListener(){
  8. @Override
  9. public void actionPerformed(ActionEvent arg0) {
  10. System.out.println("Button was clicked!");
  11. flag[0] = true;
  12. }
  13. });
  14. myFrame.add(myButton);
  15. myFrame.setSize(128,128);
  16. myFrame.setVisible(true);
  17. System.out.println("Waiting");
  18. while(!flag[0]){}
  19. System.out.println("Finished");
  20. }
  21. }

这永远不会打印“完成”,并且在点击按钮后打印一次

  1. Waiting
  2. Button was clicked!

但是,如果我修改while循环来读取

  1. while(!flag[0]){
  2. System.out.println("I should do nothing. I am just a print statement.");
  3. }

这有效!打印输出看起来像

  1. Waiting
  2. I should do nothing. I am just a print statement.
  3. I should do nothing. I am just a print statement.
  4. ....
  5. I should do nothing. I am just a print statement.
  6. Button was clicked!
  7. Finished

我理解这可能不是等待某个动作的正确方法,但我仍然有兴趣知道为什么Java会以这种方式运行.

解决方法

最有可能的原因是flag [0] = true;在UI线程上执行,而while(!flag [0])在主线程上执行.

如果没有同步,则无法保证UI线程中所做的更改将从主线程中可见.

通过添加System.out.println,您将引入同步点(因为println方法已同步)并且问题得到解决.

您可以将标志设置为易失性实例或类布尔变量(不是数组),或者更简单地,将要执行的任何代码放在侦听器本身中按下的按钮上.

作为参考,带有volatile变量的代码如下所示:

  1. private static volatile boolean flag;
  2. public static void main(String[] args) {
  3. JFrame myFrame = new JFrame("Test");
  4. JButton myButton = new JButton("Click Me!");
  5. myButton.addActionListener(new ActionListener() {
  6. @Override public void actionPerformed(ActionEvent arg0) {
  7. System.out.println("Button was clicked!");
  8. flag = true;
  9. }
  10. });
  11. myFrame.add(myButton);
  12. myFrame.setSize(128,128);
  13. myFrame.setVisible(true);
  14. System.out.println("Waiting");
  15. while (!flag) { }
  16. System.out.println("Finished");
  17. }

猜你在找的Java相关文章