为什么CountDownLatch有时在count变为零时不释放线程?

时间:2012-10-13 05:44:24

标签: java swing

我正在构建一个简单的对话框,可以通过按下按钮或Esc按钮来解除对话。我在使用CountDownLatch等待解除对话之前,并从各种监听器调用.countDown()

我遇到了以下问题 - 在窗口调用.countDown()上按“X”并导致对话框解除,而按下按钮导致调用相同的代码,但线程不会恢复执行。可能是什么问题?

Compilable / runnable示例:

import java.util.concurrent.CountDownLatch;
import javax.swing.JFrame;

public class StrangeDialog extends javax.swing.JDialog {

    final CountDownLatch latch = new CountDownLatch(1);

    public StrangeDialog(JFrame parent) {
        super(parent, true); // removing this line fixes things

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                System.out.println(latch);
                latch.countDown();
            }
        });

        setFocusable(true);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent e) {
                System.out.println(latch);
                latch.countDown();
            }
        });

        setSize(100,100);
        setVisible(true);
    }

    public static void main(String[] args) {
        StrangeDialog dialog = new StrangeDialog(null);
        try {
            dialog.latch.await();
        } catch (InterruptedException ex) {
        }
        dialog.setVisible(false);
        System.out.println("Released");
    }

}

1 个答案:

答案 0 :(得分:3)

您正在创建模态对话框。基本上,代码在窗口关闭之前不会超过StrangeDialog dialog = new StrangeDialog(null);

尝试:

final StrangeDialog dialog = new StrangeDialog(null);
SwingUtilities.invokeLater(new Runnable() { public void run() { dialog.setVisible(true); } });

在main()中打开窗口,它将按预期工作。