【发布时间】:2011-03-26 11:53:09
【问题描述】:
我正在尝试使用线程在后台运行冗长的操作并更新 UI。 这是我想要做的:
- 单击按钮时,会显示一个带有消息“正在插入 DB”的 popupjframe
- 创建一个新线程以将 1000 条条目插入数据库。
- 插入条目后,我希望 popupjframe 消失并显示一个带有是,无按钮的 joptionpane
- 单击“是”按钮后,我想显示另一个框架,其中包含有关插入过程的报告/详细信息
这是我的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//display popupframe first
jFrame1.pack();
jFrame1.setVisible(true);
jFrame1.setLocationRelativeTo(getFrame());
Thread queryThread = new Thread() {
public void run() {
runQueries();
}};
queryThread.start();
}
//runqueries method inserts into DB
private void runQueries() {
for (int i = 0; i <= 50000; i++) {
insertintoDB();
updateProgress(i);
}
}
//update the popupjframe
private void updateProgress(final int queryNo) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (queryNo == 50000) { //means insertion is done
jFrame1.setVisible(false);
int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION);
if (n == 1) { //NO option was selected
return;}
else
//display another popupframe with details/report of inserting process
}});
}
- 我的方法正确吗?
- 如何以及何时停止/中断“queryThread”?
- 如果我在 runqueries 方法本身(在 for 循环之后)创建 popupjframe 并显示 joptionpane 是否正确??
提前致谢。
【问题讨论】:
-
在你的 runQueries() 方法中,你调用 updateProgress() 50000 次,每次创建一个新线程,而只有最后一个需要做任何有用的工作。它可能并不重,但它是不必要的开销,充其量是误导性代码。 ILMTitan 是正确的:SwingWorker 是正确的方法。