[英]Java threads: let EDT function wait for long running function off the EDT
Suppose I have a function refresh() which calls two other functions, one is a long running clearData() function which needs to be run off the EDT and the other is a quick function repaint() which is run in the EDT and which repaints the GUI components. 假设我有一个函数refresh(),它调用其他两个函数,一个是运行时间较长的clearData()函数,需要在EDT上运行,另一个是快速函数repaint(),该函数在EDT中运行并重新绘制GUI组件。
refresh()
{
clearData(); //off the EDT function
repaint(); //in the EDT function
}
what is a proper way to deal with the repaint when a longer operation like clearData() need to be run. 当需要运行更长的操作(如clearData())时,处理重涂的正确方法是什么? Is it letting the clearData thread run repaint() once it is finished a proper way?
完成正确方法后,是否让clearData线程运行repaint()? how can this be done?
如何才能做到这一点?
Yes, run the repaint()
after the clearData()
is complete. 是的,在
clearData()
完成之后运行repaint()
。 You can use SwingUtilties.invokeLater()
or similar to get the repaint() to run on the EDT. 您可以使用
SwingUtilties.invokeLater()
或类似方法使repaint()在EDT上运行。
Possible implementation 可能的实施
final Runnable CLEAR_THEN_REPAINT = new Runnable() {
public void run() {
clearData();
SwingUtilities.invokeLater(new Runnable() {
public void run() { repaint(); }
});
}
};
void refresh() {
if (SwingUtilities.isEventDispatchThread()) {
new Thread(CLEAR_THEN_REPAINT).start();
} else {
CLEAR_THEN_REPAINT.run();
}
}
refresh() {
new Runnable(){
clearData();
SwingUtilities.invokeLater(new Runnable() {
repaint();
});
}.run();
}
Notice that repaint will be registered to be invoked after clearData();
请注意,将在
clearData();
之后注册重画以进行调用clearData();
has returned, so, it's guaranteed that repaint()
will execute after clearData()
. 已经返回,因此可以确保
repaint()
将在clearData()
之后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.