我做了一个样本来说明问题:
public class Worker extends SwingWorker<Integer, Integer> {
private GeneralUserInterface gui;
public Worker(GeneralUserInterface gui){
this.gui = gui;
}
@Override
protected Integer doInBackground() throws Exception {
int someResultToReturn = 10;
for(int i=0; i<100; i++){
Thread.sleep(50);//The Work
publish(i+1);//calls process, which updates GUI
}
return someResultToReturn;
}
@Override
protected void process(List<Integer> values) {
for (Integer val : values) {
gui.updateProgressBar(val);
}
}
}
private void jButtonDoWorkActionPerformed(java.awt.event.ActionEvent evt) {
Worker worker = new Worker(this);
worker.execute();
try {
int resultToGet = worker.get();//Obviously freezes the GUI
} catch (InterruptedException | ExecutionException ex) {}
//NEXT LINE NEEDS THE RESULT TO CONTINUE
}
public void updateProgressBar(int value){
this.jProgressBar1.setValue(value);
}
正如您所猜测的,对 worker.get() 的调用使 UI 无响应,这是正常的,因为它等待线程完成。这类问题一般是怎么解决的?