没有冻结的Java长计算GUI(单线程)

时间:2016-01-06 03:11:46

标签: java

在采访中,我被问到问题:"如何在单线程中执行许多计算而不冻结GUI组件(如进度条)或者能够检查另一个用户输入? (只能执行一个线程)"

我被问到可以编写像Node.js这样的事件循环。 但我说Java已经有了一些机制。那个java可以使用硬件并行化操作。这个类或特殊词可用于此任务的内容是什么?

1 个答案:

答案 0 :(得分:3)

因此,假设我们无法使用SwingWorker或Swing Timer,因为他们创建了第二个线程来支持他们的操作,您唯一的选择就是使用SwingUtilities#invokeLater重复调用一个方法,该方法执行一小部分工作并在再次调用之前更新UI(使用SwingUtilities#invokeLater

Look ma, no threads

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class NoMoreThreads {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final int MAX = 1000;

        private JProgressBar pb;
        private JButton start;
        private int count;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            start = new JButton("Let's get this party started");
            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    start.setEnabled(false);
                    calculate();
                }
            });

            pb = new JProgressBar(0, MAX);

            add(start, gbc);
            add(pb, gbc);
        }

        protected void calculate() {
            count++;
            if (count < MAX) {
                pb.setValue(count);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        calculate();
                    }
                });
            } else {
                start.setEnabled(true);
            }
        }

    }

}