【问题标题】:Show an indeterimante progress bar in a JDialog in a thread and run a task in another thread concurrently在线程中的 JDialog 中显示不确定的进度条并同时在另一个线程中运行任务
【发布时间】:2012-08-19 18:27:16
【问题描述】:

当用户单击按钮时,将运行大约 10 秒的长任务。在此期间,我想向用户显示进度条。但是主线程必须等待工作线程完成,因为工作线程将设置一个主线程将使用的变量。如果我不等待工作线程,我将在使用变量时得到NullPointerException。所以在工作线程完成后,我也会关闭进度条对话框。

当我使用join() 等待工作线程时,进度条对话框显示(有趣的是没有进度条)并挂在那里。

Thread runnable = new Thread() {

    public void run() {
        try {
            System.out.println("thread basladi");
            threadAddSlaveReturnMessage = request.addSlave(
                ipField.getText(), passField.getText(), 
                nicknameField.getText());
            System.out.println("thread bitti");

        } catch (LMCTagNotFoundException e) {
            e.printStackTrace();
        }

    }
};

Thread runnable_progress = new Thread() {

    public void run() {

        JTextArea msgLabel;
        JDialog dialog;
        JProgressBar progressBar;
        final int MAXIMUM = 100;
        JPanel panel;

        progressBar = new JProgressBar(0, MAXIMUM);
        progressBar.setIndeterminate(true);
        msgLabel = new JTextArea("deneme");
        msgLabel.setEditable(false);


        panel = new JPanel(new BorderLayout(5, 5));
        panel.add(msgLabel, BorderLayout.PAGE_START);
        panel.add(progressBar, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createEmptyBorder(11, 11, 11, 11));

        dialog = new JDialog(Frame.getFrames()[0], "baslik", true);
        dialog.getContentPane().add(panel);
        dialog.setResizable(false);
        dialog.pack();
        dialog.setSize(500, dialog.getHeight());
        dialog.setLocationRelativeTo(null);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setAlwaysOnTop(false);
        dialog.setVisible(true);
        msgLabel.setBackground(panel.getBackground());
    }
};

runnable.start();
System.out.println("runnable start");
runnable_progress.start();
System.out.println("progress start");
runnable.join();
System.out.println("runnable join");
runnable_progress.join();
System.out.println("progress join");


if (threadAddSlaveReturnMessage.equalsIgnoreCase("OK")) {
    fillInventoryTable(inventoryTable);
    JOptionPane.showMessageDialog(this, messages.getString("centrum.addslavepanel.SUCCESS"), null, JOptionPane.INFORMATION_MESSAGE);
}

“进度加入”

不打印。

【问题讨论】:

  • 在进入细节之前:Swing 的第一条规则(与并发相关)是所有组件访问必须发生在 EDT 上。请阅读Swing标签中引用的教程中的相关章节:-)
  • 如需尽快获得更好的帮助,请发帖SSCCE。

标签: java multithreading swing concurrency runnable


【解决方案1】:

您可以在此处使用SwingWorker。一个简短的例子:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.godel.nio;

import java.awt.BorderLayout;
import java.util.List;
import javax.swing.*;

/**
 *
 * @author internet_2
 */
public class Test {

    public static void main(String[] args) {
        new Test().doJob();
    }

    public void doJob() {

        JTextArea msgLabel;
        JProgressBar progressBar;
        final int MAXIMUM = 100;
        JPanel panel;

        progressBar = new JProgressBar(0, MAXIMUM);
        progressBar.setIndeterminate(true);
        msgLabel = new JTextArea("deneme");
        msgLabel.setEditable(false);

        panel = new JPanel(new BorderLayout(5, 5));
        panel.add(msgLabel, BorderLayout.PAGE_START);
        panel.add(progressBar, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createEmptyBorder(11, 11, 11, 11));

        final JDialog dialog = new JDialog();
        dialog.getContentPane().add(panel);
        dialog.setResizable(false);
        dialog.pack();
        dialog.setSize(500, dialog.getHeight());
        dialog.setLocationRelativeTo(null);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setAlwaysOnTop(false);
        dialog.setVisible(true);
        msgLabel.setBackground(panel.getBackground());

        SwingWorker worker = new SwingWorker() {

            @Override
            protected void done() {
                // Close the dialog
                dialog.dispose();
            }

            @Override
            protected void process(List chunks) {
                // Here you can process the result of "doInBackGround()"
                // Set a variable in the dialog or etc.
            }

            @Override
            protected Object doInBackground() throws Exception {
                // Do the long running task here
                // Call "publish()" to pass the data to "process()"
                // return something meaningful
                return null;
            }
        };

        worker.execute();

    }
}

编辑:应在“doInBackground()”中调用“publish()”以将数据传递给“process()”。

【讨论】:

  • +1 一个小建议:您可以提到在 doInBackground 中调用 publish(带有中间结果) - 因为不这样做是一个常见的错误/误解 :-)
  • 这里也有同样的问题。我必须等待 dojob 功能完成。因为该函数将设置一个变量。如果我不设置它,我会得到一个空指针异常。正如您在我发布的代码中看到的那样,我正在长时间运行的任务中设置 threadAddSlaveReturnMessage 变量。如果我不等待它,我会得到一个空指针异常。如果我等待它,那么会出现没有进度条的进度条对话框 :D 并永远挂在那里。
  • 顺便说一句,等待任务完成意味着使用 worker.get();在worker.execute()之后;
  • 另见Initial Threads。
【解决方案2】:
  1. Concurency is Swing 有问题,所有线程完成后您的 GUI 可见

  2. 可以和JProgressBar一起移动(我说的是你的代码)但你必须这样做

    • 创建并显示JDialog,创建一次并重复使用此容器

    • 然后开始Thread,

    • 最好来自Runnable#Thread

    • 到 Swing GUI 的输出必须包装到 invokeLater()

  3. 这正是使用 SwingWorker 和 PropertyChangeListener 的工作

【讨论】:

    【解决方案3】:

    正如前面的答案已经提到的,SwingWorker 是要走的路,如果用户想在 Swing 中使用并发。
    我发现这个SwingWorker and ProgressBar tutorial 对于理解它们如何协同工作非常有用。

    回到您的实际问题:我假设您使用 GUI,因为您声明用户必须单击一个按钮。问题是,你的“主线程”在做什么?它真的必须一直运行吗?看起来不像。因为您说线程需要一个由另一个线程设置的变量,这是用户交互的结果。简而言之:如果它依赖于用户交互,为什么还需要运行?
    通常的方法是首先获取您需要的所有数据,然后运行计算或其他方式。在您的情况下,要么在单个后台线程中运行所有内容(首先设置变量,然后执行其余部分),由按钮的 ActionListener 启动,要么在您设置变量的线程之后运行另一个线程已完成。
    例如,您可以使用SwingWorker 提供的方法done() 来启动下一个任务。或者如果你真的需要,你可以循环等待task.isDone()返回true。但也不要忘记检查isCancelled()。

    无论如何,我认为你应该重新考虑你的设计。因为我从提供的有限信息中看到的对我来说过于复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-12
      • 2010-12-16
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多