编程语言
首页 > 编程语言> > Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker

Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker

作者:互联网

我有一个SwingWorker如下:

public class MainWorker extends SwingWorker(Void, MyObject) {
    :
    :
}

我从EDT调用了上面的Swing Worker:

MainWorker mainWorker = new MainWorker();
mainWorker.execute();

现在,mainWorker创建了MyTask类的10个实例,以便每个实例都可以在自己的线程上运行,从而更快地完成工作.

但问题是我想在任务运行时不时更新gui.我知道如果任务是由mainWorker本身执行的,我可以使用publish()和process()方法来更新gui.

但是由于任务是由不同于Swingworker线程的线程执行的,我如何从执行任务的线程生成的中间结果更新gui.

解决方法:

SwingWorker的API文档提供了以下提示:

The doInBackground() method is called
on this thread. This is where all
background activities should happen.
To notify PropertyChangeListeners
about bound properties changes use the
firePropertyChange and
getPropertyChangeSupport() methods. By
default there are two bound properties
available: state and progress.

MainWorker可以实现PropertyChangeListener.然后它可以使用PropertyChangeSupport注册自己:

getPropertyChangeSupport().addPropertyChangeListener( this );

MainWorker可以将其PropertyChangeSupport对象提供给它创建的每个MyTask对象.

new MyTask( ..., this.getPropertyChangeSupport() );

然后,MyTask对象可以使用PropertyChangeSupport.firePropertyChange方法通知其MainWorker进度或属性更新.

然后,通知的MainWorker可以使用SwingUtilities.invokeLater或SwingUtilities.invokeAndWait通过EDT更新Swing组件.

protected Void doInBackground() {
    final int TASK_COUNT = 10;
    getPropertyChangeSupport().addPropertyChangeListener(this);
    CountDownLatch latch = new CountDownLatch( TASK_COUNT ); // java.util.concurrent
    Collection<Thread> threads = new HashSet<Thread>();
    for (int i = 0; i < TASK_COUNT; i++) {
        MyTask task = new MyTask( ..., latch, this.getPropertyChangeSupport() ) );
        threads.add( new Thread( task ) );
    }
    for (Thread thread: threads) {
        thread.start();
    }
    latch.await();
    return null;
}

标签:java,user-interface,swingworker
来源: https://codeday.me/bug/20190715/1463650.html