停止/取消 SwingWorker 线程?

2022-09-01 15:10:12

我正在尝试找出如何在按下按钮时阻止SwingWorker线程运行。我一直在四处寻找,我在弄清楚如何做到这一点时遇到了一些麻烦。目前,这就是我所拥有的:

new MySwingWorkerClass(args).execute();

然后,我正在创建一个按钮,我想使用它来停止线程:

button = new JButton("Stop");
button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) 
        {
        // Stop the swing worker thread
        }
});

我已经四处寻找答案,到目前为止,我已经设法找到了取消方法。我不明白如何用它来阻止我的摇摆工人。我尝试了以下方法,但它不起作用:

SwingWorker.cancel(true);

答案 1

您需要保留对 SwingWorker 的引用,然后使用该引用取消工作线程。

MySwingWorker myWorker = new MySwingWorkerClass(args).execute();

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) 
    {
        // Stop the swing worker thread
        myWorker.cancel(true);
    }
});

下面是一个完整的示例:

enter image description here

public class WorkerDemo extends JFrame {
    private boolean isStarted = false;
    private JLabel counterLabel = new JLabel("Not started");
    private Worker worker = new Worker();
    private JButton startButton = new JButton(new AbstractAction("Start") {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if(!isStarted) { 
                worker.execute();
                isStarted = false;
            }
        }

    });
    private JButton stopButton = new JButton(new AbstractAction("Stop") {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            worker.cancel(true);
        }

    });

    public WorkerDemo() {

        add(startButton, BorderLayout.WEST);
        add(counterLabel, BorderLayout.CENTER);
        add(stopButton, BorderLayout.EAST);
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class Worker extends SwingWorker<Void, Integer> {

        int counter = 0;

        @Override
        protected Void doInBackground() throws Exception {
            while(true) {
                counter++;
                publish(counter);
                Thread.sleep(60);
            }
        }

        @Override
        protected void process(List<Integer> chunk) {

            // get last result
            Integer counterChunk = chunk.get(chunk.size()-1);

            counterLabel.setText(counterChunk.toString());
        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new WorkerDemo();
            }

        });
    }

}

答案 2

您需要定期检查其已取消的标志(即 isCancelled())。SwingWorker将如何处理中断留给您。

有关详细信息,请参阅取消后台任务


推荐