【发布时间】:2011-11-24 17:00:20
【问题描述】:
可能重复:
How do I wait for a SwingWorker's doInBackground() method?
我读到这样做真的很糟糕,但我认为这是实现目标的最佳方式...... 有没有办法阻塞主线程,直到下例中的 swing worker 完成?
public void flashNode(Node node, int noOfFlashes) {
GraphUpdater updater = new GraphUpdater(node, noOfFlashes);
updater.execute();
}
还有SwingWorker 类
public class GraphUpdater extends SwingWorker<Integer, Integer> {
Node node;
int noOfFlashes;
public GraphUpdater(Node n, int noFlashes) {
node = n;
noOfFlashes = noFlashes;
}
@Override
protected Integer doInBackground() throws Exception {
Color origColor = node.getColor();
for (int i=0; i<noOfFlashes; i++) {
changeNodeColor(node, Color.WHITE);
Thread.sleep(500);
changeNodeColor(node, origColor);
Thread.sleep(500);
}
return 1;
}
}
提前致谢
【问题讨论】:
-
但是如果你想首先阻塞主 UI 线程,为什么要使用 Swingworker 呢?您可以在主线程中运行代码。
标签: java multithreading swing swingworker