swingworker--Tasks that Have Interim Results

本文介绍如何使用 SwingWorker 在 Java 中实现后台任务并提供进度更新。通过示例程序 Flipper,展示如何生成随机布尔值模拟掷硬币实验,并通过 GUI 实时显示结果。

Tasks that Have Interim Results

 

It is often useful for a background task to provide interim results while it is still working. The task can do this by invoking SwingWorker.publish. This method accepts a variable number of arguments. Each argument must be of the type specified by SwingWorker's second type parameter.

To collect results provided by publish, override SwingWorker.process This method will be invoked from the event dispatch thread. Results from multiple invocations of publish are often accumulated for a single invocation of process.

Let's look at the way the Flipper.java example uses publish to provide interim results. Click the Launch button to run Flipper using Java™ Web Start (download JDK 6). Or, to compile and run the example yourself, consult the example index.

This program tests the fairness of java.util.Random by generating a series of random boolean values in a background task. This is equivalent to flipping a coin; hence the name Flipper. To report its results, the background task uses an object of type FlipPair

private static class FlipPair {

    private final long heads, total;

    FlipPair(long heads, long total) {

        this.heads = heads;

        this.total = total;

    }

}

The heads field is the number of times the random value has been true; the total field is the total number of random values.

The background task is represented by an instance of FlipTask:

private class FlipTask extends SwingWorker<Void, FlipPair> {

Since the task does not return a final result, it does not matter what the first type parameter is; Void is used as a placeholder. The task invokes publish after each "coin flip":

@Override

protected Void doInBackground() {

    long heads = 0;

    long total = 0;

    Random random = new Random();

    while (!isCancelled()) {

        total++;

        if (random.nextBoolean()) {

            heads++;

        }

        publish(new FlipPair(heads, total));

    }

    return null;

}

(The isCancelled method is discussed in the next section.) Because publish is invoked very frequently, a lot of FlipPair values will probably be accumulated before process is invoked in the event dispatch thread; process is only interested in the last value reported each time, using it to update the GUI:

protected void process(List<FlipPair> pairs) {

    FlipPair pair = pairs.get(pairs.size() - 1);

    headsText.setText(String.format("%d", pair.heads));

    totalText.setText(String.format("%d", pair.total));

    devText.setText(String.format("%.10g",

            ((double) pair.heads)/((double) pair.total) - 0.5));

}

 

 

public class Flipper extends JFrame

                  implements ActionListener {

    private final GridBagConstraints constraints;

    private final JTextField headsText, totalText, devText;

    private final Border border =

        BorderFactory.createLoweredBevelBorder();

    private final JButton startButton, stopButton;

    private FlipTask flipTask;

 

    private JTextField makeText() {

        JTextField t = new JTextField(20);

        t.setEditable(false);

        t.setHorizontalAlignment(JTextField.RIGHT);

        t.setBorder(border);

        getContentPane().add(t, constraints);

        return t;

    }

 

    private JButton makeButton(String caption) {

        JButton b = new JButton(caption);

        b.setActionCommand(caption);

        b.addActionListener(this);

        getContentPane().add(b, constraints);

        return b;

    }

    public Flipper() {

        super("Flipper");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        //Make text boxes

        getContentPane().setLayout(new GridBagLayout());

        constraints = new GridBagConstraints();

        constraints.insets = new Insets(3, 10, 3, 10);

        headsText = makeText();

        totalText = makeText();

        devText = makeText();

 

        //Make buttons

        startButton = makeButton("Start");

        stopButton = makeButton("Stop");

        stopButton.setEnabled(false);

 

        //Display the window.

        pack();

        setVisible(true);

    }

 

    private static class FlipPair {

        private final long heads, total;

        FlipPair(long heads, long total) {

            this.heads = heads;

            this.total = total;

        }

    }

 

    private class FlipTask extends SwingWorker<Void, FlipPair> {

        @Override

        protected Void doInBackground() {

            long heads = 0;

            long total = 0;

            Random random = new Random();

            while (!isCancelled()) {

                total++;

                if (random.nextBoolean()) {

                    heads++;

                }

                publish(new FlipPair(heads, total));

            }

            return null;

        }

 

        @Override

        protected void process(List<FlipPair> pairs) {

            FlipPair pair = pairs.get(pairs.size() - 1);

            headsText.setText(String.format("%d", pair.heads));

            totalText.setText(String.format("%d", pair.total));

            devText.setText(String.format("%.10g",

                    ((double) pair.heads)/((double) pair.total) - 0.5));

        }

    }

 

 

 

    public void actionPerformed(ActionEvent e) {

        if ("Start" == e.getActionCommand()) {

            startButton.setEnabled(false);

            stopButton.setEnabled(true);

            (flipTask = new FlipTask()).execute();

        } else if ("Stop" == e.getActionCommand()) {

            startButton.setEnabled(true);

            stopButton.setEnabled(false);

            flipTask.cancel(true);

            flipTask = null;

        }

 

    }

 

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new Flipper();

            }

        });

    }

}

 

内容概要:本文围绕EKF SLAM(扩展卡尔曼滤波同步定位与地图构建)的性能展开多项对比实验研究,重点分析在稀疏与稠密landmark环境下、预测与更新步骤同时进行与非同时进行的情况下的系统性能差异,并进一步探讨EKF SLAM在有色噪声干扰下的鲁棒性表现。实验考虑了不确定性因素的影响,旨在评估不同条件下算法的定位精度与地图构建质量,为实际应用中EKF SLAM的优化提供依据。文档还提及多智能体系统在遭受DoS攻击下的弹性控制研究,但核心内容聚焦于SLAM算法的性能测试与分析。; 适合人群:具备一定机器人学、状态估计或自动驾驶基础知识的科研人员及工程技术人员,尤其是从事SLAM算法研究或应用开发的硕士、博士研究生和相关领域研发人员。; 使用场景及目标:①用于比较EKF SLAM在不同landmark密度下的性能表现;②分析预测与更新机制同步与否对滤波器稳定性与精度的影响;③评估系统在有色噪声等非理想观测条件下的适应能力,提升实际部署中的可靠性。; 阅读建议:建议结合MATLAB仿真代码进行实验复现,重点关注状态协方差传播、观测更新频率与噪声模型设置等关键环节,深入理解EKF SLAM在复杂环境下的行为特性。稀疏 landmark 与稠密 landmark 下 EKF SLAM 性能对比实验,预测更新同时进行与非同时进行对比 EKF SLAM 性能对比实验,EKF SLAM 在有色噪声下性能实验
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值