【问题标题】:Java: How to make a thread wait on IO from user and then proceedJava:如何让线程等待用户的 IO 然后继续
【发布时间】:2012-12-10 04:09:11
【问题描述】:

在 DbInterface 类中,函数 openDB() 打开与服务器上的 Oracle DB 的连接。出于安全原因,用户必须在 JFrame 文本区域中输入密码,然后程序才能继续连接。现在这个 Jframe 有一个动作监听器,它等待用户输入密码并调用 OpenDBContinue() 方法。

现在的问题是:openDB() 不等待 Jframe IO 完成并假设 DB 已打开,将控制权返回给调用类(调用 openDB() 的人),然后他们继续开始查询 DB,这显然失败!

现在如何让 openDB() 等待 Jframe IO 完成?这是给你一个想法的代码。

public void openDB(int inFileInx,String inRemoteDBURLFull) throws FileNotFoundException
{   
    if(this.password!=null)
        try
        {   openDBcontinue(inFileInx,inRemoteDBURLFull);
        }
        catch(Exception exp)
            {   DpmLogger.dtlException("SPDBInterfaceException:OpenDB", exp);
            }
    else {
            passwd  =       new JFrame();
            passwd.setLocation(SpdMain.bTabbedPanel.getWidth()/2,SpdMain.bTabbedPanel.getHeight()/2);
            passwd.setTitle("Enter Passwd for user "+username);
            JPasswordField p =new JPasswordField(10);
            p.addActionListener(this);
            p.setActionCommand(inFileInx+","+inRemoteDBURLFull);
            passwd.add(p);
            passwd.setPreferredSize(new Dimension(300,50));
            passwd.pack();
            passwd.setVisible(true);
            pass=new Thread(new Runnable()  
            {   
                public void run() {
                    DpmLogger.dtlTraceOut("The password thread has completed and has got password from the user",DpmLogger.TRACE_RARE,myId);
                }

            });

            try {
                    pass.join();
                } catch (InterruptedException e) 
                    {
                        DpmLogger.dtlTraceOut("Password thread unable to join",DpmLogger.TRACE_RARE,myId);
                    }

                DpmLogger.dtlTraceOut("Password thread now joined",DpmLogger.TRACE_RARE,myId);
        }

}


public void actionPerformed(ActionEvent e) 
{   JTextField p=(JTextField)e.getSource();
    if(password==null)
    password=p.getText();
    passwd.setVisible(false);

    String[] inVars=e.getActionCommand().split(",");
    try
    {   openDBcontinue(Integer.parseInt(inVars[0]),inVars[1]);
             pass.start();
    }
    catch(Exception exp)
    {   DpmLogger.dtlException("SPDBInterfaceException:OpenDB", exp);
    }
}

如您所见,我正在尝试使用 join() 使该方法在“通过”线程上等待。当 IO 完成时,动作监听器启动 pass 线程。但它不起作用。 OpenDB() 无需等待“通过”运行即可返回。这是因为该方法不在线程内吗?我必须让这个 DBInterface 类扩展 Thread 类吗?我很困惑!

【问题讨论】:

  • JDialog 有什么问题?
  • 所有事件都在swing中的单独线程(事件调度线程)中处理。我认为您在错误的线程中应用了pass.join()(这使得 current 线程等待通过完成),而您想等待 JFrame IO 完成。如果有任何耗时的处理,你应该考虑SwingWorker,这样你的 UI 就不会冻结
  • 抱歉,我确实使用了 JPasswordField(你可以在代码中看到它)。我一定忘了提,但这不是我的问题

标签: java multithreading swing io


【解决方案1】:

出于安全原因,用户必须在 JFrame 文本区域中输入密码

为:

  1. 方便(和可能的解决方案)将JFrame 换成模态对话框或JOptionPane。例如。如this answer中所见。
  2. 安全性使用JPassWordField 而不是the tutorial 中看到的“textarea”。

【讨论】:

  • 我使用 JPasswordField。正确查看代码。还是谢谢!
  • “正确查看代码。”正确拼写类名。如果需要,复制/粘贴它们。 'textarea' 不是 JPasswordField。
【解决方案2】:

您可以使用JDialog,但这需要您管理关闭操作(添加按钮和搞乱状态),或者您可以简单地使用JOptionPane

任何一个(当设置为模态时)都会导致事件调度线程在该点暂停执行,直到它们被关闭。

public class TestDialog01 {

    public static void main(String[] args) {
        new TestDialog01();
    }

    public TestDialog01() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                PasswordPane pane = new PasswordPane();
                int result = JOptionPane.showConfirmDialog(null, pane, "Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    // get the result...
                }

            }
        });
    }

    public class PasswordPane extends JPanel {

        private JTextField userName;
        private JPasswordField password;

        public PasswordPane() {
            userName = new JTextField(12);
            password = new JPasswordField(12);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(new JLabel("User Name:"), gbc);
            gbc.gridx++;
            add(userName, gbc);

            gbc.gridy++;
            gbc.gridx = 0;
            add(new JLabel("Password:"), gbc);
            gbc.gridx++;
            add(password, gbc);
        }

        public String getUserName() {

            return userName.getText();

        }

        public char[] getPassword() {

            return password.getPassword();

        }
    }
}

查看How to Make Dialogs了解更多信息

【讨论】:

  • 那么,您不会从事件调度线程中调用 OpenDB。
  • 还是不行。 OpenDB() 总是返回不等待 JOptionPane 返回 OK_OPTION。发生这种情况:openDB 调用 joptionPane 将显示对话框 openDBreturns back to filemgr after calling openDB joptionpane: password is records as test
  • JOptionPane 必须在 EDT 中可见才能阻塞线程。你有一些示例代码吗?
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2016-09-13
  • 2018-05-19
相关资源
最近更新 更多