我正在玩SwingWorker并学习使用它。所以,我有这段代码:
ArrayList<Train> dataList = new ArrayList<>();
ArrayList<Train> proccessedData = new ArrayList<>();
String query = "my query, not relevant here";
dataList = myApi.getTrainData(connectServer(), query, false);
TestNewThread tpp = new TestNewThread(dataList, threshold, pairs, false);
tpp.execute();
我的TestNewThread类是:
public class TestNewThread extends SwingWorker<List, String>{
private ArrayList<Train> dataList;
private int threshold
private int pair
private boolean processFurther)
MyAPI myApi = MyAPI.getInstance();
public TestNewThread(ArrayList<Train> dataList, int threshold, int pair, boolean processFurther) {
this.dataList = dataList;
this.threshold = threshold
this.pair = pair
this.iprocessFurther) = processFurther)
}
@Override
protected List doInBackground() throws Exception {
ArrayList<Train> list;
publish("Starting process");
list = processingTrains(threshold, pair, dataList);
publish("Process finished.");
return list;
}
@Override
protected void process(List<String> chunks) {
String mostRecentValue = chunks.get(chunks.size() - 1);
myApi.printPanel("\n"+mostRecentValue);
}
@Override
protected void done() {
// myApi .printPanel("\nALL DONE... !);
}
现在我需要什么,我无法弄清楚如何做到这一点:
在这里的第一个代码,我tpp.execute();
我希望它返回到指定的变量。对于这样的事情,请注意评论部分:
ArrayList resultsList = new ArrayList();
TestNewThread tpp = new TestNewThread(dataList, threshold, pairs, false);
resultsList = tpp.execute(); // I know I can't do this because .execute() is void but I want something like whatever the new thread returns to return to resultsList array.
如果代码中有任何拼写错误或遗漏,我很抱歉,我现在就从头顶解释我的问题。我想你可以从这里得到这个想法。
答案 0 :(得分:1)
SwingWorker的重点是能够异步执行某些操作,而不会阻塞EDT线程。因此,您无法从tpp.execute()
返回任何内容,因为如果可以,那将意味着在后台任务完成之前EDT将被阻止,并且后台任务将不再是后台任务。< / p>
但是,您可以使用SwingWorker传递对组件的引用,并从done()方法调用此组件的方法:
public class SomePanel extends JPanel {
...
TestNewThread tpp = new TestNewThread(this, dataList, threshold, pairs, false);
tpp.execute();
...
public void backgroundTaskHasFinishedHereIsTheResult(List<Train> trains) {
// TODO do whatever with the list of trains computed by the background task
}
}
在SwingWorker子类中:
private SomePanel somePanel;
public TestNewThread(SomePanel somePanel, ArrayList<Train> dataList, int threshold, int pair, boolean processFurther) {
this.somePanel = somePanel;
...
}
@Override
protected void done() {
List<Train> result = get();
somePanel.backgroundTaskHasFinishedHereIsTheResult(result);
}