陷入while(true)循环内部。如何在线程中隔离它?

时间:2013-06-30 23:33:33

标签: java while-loop runnable

这是run()方法:

public void run() {         
    ServerSocket listener = null;           
    if (running == true) {
        btnRun.setEnabled(false);
        try {
            if (!(portField.getText().equals(""))) {                
                String p = portField.getText();
                if (p.matches("[0-9]*")) {                          
                    listener = new ServerSocket(Integer.parseInt(p));                           
                    while (true) {
                        Socket socket = listener.accept();
                        try {
                            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                            out.println("Hi there, human.");    
                        } finally {
                            socket.close(); 
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Only numbers are allowed.");
                    btnRun.setEnabled(true);
                    running = 
                }
            } else {
                JOptionPane.showMessageDialog(null, "Please input a port.");
                btnRun.setEnabled(true);
                running = false;
            }
        } catch (NumberFormatException | HeadlessException | IOException e) {               
            e.printStackTrace();
        }
    } else {
        btnRun.setEnabled(true);
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException e) {                       
                e.printStackTrace();
            }
        }
    }
}

这是按钮:

btnRun = new JButton("Run Server");
btnRun.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (running == false) {
            running = true;
                run();
        }
    }               
});

单击该按钮时,软件会冻结(它会在while(true)循环内无限地运行)。据我所知,我需要在一个单独的“线程”中运行此循环,并在另一个中运行GUi。但问题是:我认为我通过实现Runnable接口正是这样做的。

如何在线程中隔离(true),以便我可以使用GUI的其余部分,包括"JFrame.EXIT_ON_CLOSE"*

1 个答案:

答案 0 :(得分:10)

只是实现Runnable是不够的,你需要显式启动一个线程:

Thread myThread = new Thread(myRunnable);
myThread.start();