SwingWorker 的 API 文档提供了这样的提示:
调用 doInBackground() 方法
在这个线程上。这就是所有
应该发生后台活动。
通知 PropertyChangeListener
关于绑定属性更改使用
firePropertyChange 和
getPropertyChangeSupport() 方法。经过
默认有两个绑定属性
可用:状态和进度。
MainWorker
可以实施PropertyChangeListener
。然后它可以向其注册自己PropertyChangeSupport
:
getPropertyChangeSupport().addPropertyChangeListener( this );
MainWorker
可以供应其PropertyChangeSupport
反对每一个MyTask
它创建的对象。
new MyTask( ..., this.getPropertyChangeSupport() );
A MyTask
然后对象可以通知它的MainWorker
进度或属性更新通过使用PropertyChangeSupport.firePropertyChange
方法。
MainWorker
,如此通知,然后可以使用SwingUtilities.invokeLater
or 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;
}