0

我有一个按钮,单击该按钮时需要生成一个带有 ProgressBar 的对话框来跟踪 CompletionService 的任务完成情况。在将其标记为重复之前,我不认为这是一个 EDT 问题,因为 ProgressBarRunnable 是单独的线程。

以下是按钮单击和相关工作人员的代码:

        public static class WorkerRunnable implements Runnable {

        int taskCards;
        TaskManagerInterface ti;
        CompletionService ecs;
        PropertyChangeSupport pcs;

        public WorkerRunnable(int taskCards, TaskManagerInterface ti, CompletionService ecs, PropertyChangeSupport pcs) {
            this.taskCards = taskCards;
            this.ti = ti;
            this.ecs = ecs;
            this.pcs = pcs;
        }

        @Override
        public void run() {
            for (int i2 = 0; i2 < taskCards; i2++) {
                System.out.println("task=" + i2 + " of " + taskCards);
                try {
                    Future<Object> take = ecs.take();
                    TaskCard get = (TaskCard) take.get();
                    ti.deployTask(get);
                    Thread.sleep(1000);
                    pcs.firePropertyChange(ProgressBarUI.PROGRESS, taskCards, i2);
                } catch (InterruptedException ex) {
                    System.out.println("EXCEPTION!");
                    Exceptions.printStackTrace(ex);
                } catch (ExecutionException ex) {
                    Exceptions.printStackTrace(ex);
                }

            }
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        ExecutorService pool = Executors.newFixedThreadPool(5);
        CompletionService<Object> ecs = new ExecutorCompletionService<>(pool);
        ArrayList<TaskCard> taskCards = ti.getTaskCards();
        Iterator<TaskCard> i = taskCards.iterator();
        ProgressBarUI pb = new ProgressBarUI(dialog, "Submitting Tasks", true);
        pcs.addPropertyChangeListener(pb);

        while (i.hasNext()) {
            TaskCard tc = i.next();
            ecs.submit(new SubmitCallable(ti, ci, tc));
        }
        SwingUtilities.invokeLater(new WorkerRunnable(taskCards.size(), ti, ecs, pcs));
        pb.setLocationRelativeTo(dialog);
        pb.setVisible(true);

        System.out.println("Done!");
    }
4

0 回答 0