SwingWorker的API文档提供了以下提示:
doInBackground()方法在此线程上调用。这是所有后台活动应该发生的地方。要通知PropertyChangeListeners有关绑定属性更改,请使用firePropertyChange和getPropertyChangeSupport()方法。默认情况下,有两个可用的绑定属性:state和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 );
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;
}
Object
发布到GUI,以用于填充JTable
。 - Amit