【发布时间】:2015-10-04 19:25:04
【问题描述】:
我有一个小的 java 程序,使用 WindowBuilder 在 Eclipse 中编写,它可以从 UTF-8 文本文件中读取数据并将它们写入数据库。为了保持 GUI 的响应能力,我使用了一个摆动工作线程,在单击按钮时执行。
btnex.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
worker = new SwingWorker<Void, Void>() {
public Void doInBackground() {
String[] content = Reader.getContent(file);
//do something with the content, if something goes wrong, set error to true.
return null;
}
public void done() {
if (!error) {
//handle error
}
};
worker.execute();
Reader 类中的 getContent 函数将文件中的数据提取到字符串数组中。
public static String[] getContent (String dbfile) {
try {
String[] lines = null;
String[] linesplit = null;
String store = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(dbfile), "UTF8"));
String line = "";
line = reader.readLine();
linesplit = line.split(";");
while (linesplit.length > 1 && !line.equals(null)) {
for (int i = 0; i < linesplit.size(); i++) {
store += StringFormer.decrypt(linesplit[i]) + " ";
} //StringFormer is another class written by me, just for decrypting the string
store += "\n";
line = reader.readLine();
if (line.equals(null)) break;
linesplit = line.split(";");
}
reader.close();
lines = store.split("\n");
return lines;
} catch (Exception ex) { //...
}
}
当我尝试运行我的程序并单击按钮时,该程序无法正常运行。所以我在调试模式下运行程序,结果,thead 没有完成,而是在完成所有工作之前以某种方式退出。这发生在 getContent 中,在离开 while 循环之后但在处理 reader.close() 之前。在离开while循环之前,调试视图中的调用堆栈包含按钮单击和getContent的调用,旁边是其他的,但是一旦我离开循环,上面提到的两个就被丢弃了,下一个堆栈成员命名为基础摇摆工人类:SwingWorker$2(FutureTask).run.
有谁知道,为什么程序没有完成编写的工作流程?我在程序中使用多个线程,但从来没有两个后台线程同时运行。
【问题讨论】:
-
你在任何地方都给
worker.get()打电话吗?您可能需要调用它来检索 SwingWorker 抛出的任何异常。 -
(1)“程序不能正常工作”——到底发生了什么?例外?缺少结果? (2) 我不认为调用
SwingWorker.publish是要求,它在内部调用你的SwingWorker.process方法,仅仅使用它们不太可能解决你的问题,但它可能会有所帮助缩小错误的范围。 -
@DSlomer64: 不确定第 (3) 点是否适合我,但是应该在 SwingWorker 完成时调用
get()方法,我自己通常在 PropertyChangeListener 中执行此操作,监听newValue == SwingWorker.StateValue.DONE。这样做可以防止调用 get 阻塞 EDT,并将调用 get 和获取异常的责任放在调用代码上(而不是从done()方法中调用它)。 -
我删除了第 (3) 点。它在那里是因为我使用了几次
SwingWorker,并认为我没有使用get。当我发现 I DID 时,我删除了 (3)。最近我用一个 Android 应用程序完成了doInBackground,但它没有在那里使用。搞糊涂了。存在的其他原因与阻止有关的警告一样。
标签: java multithreading swing backgroundworker interrupt