0

我正在玩 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.

如果代码中有任何拼写错误或其他内容,我很抱歉,我现在只是从头顶上解释我的问题。我想你可以从这里得到这个想法。

4

1 回答 1

1

SwingWorker 的全部意义在于能够异步执行某些操作,而不会阻塞 EDT 线程。因此,您无法从 中返回任何内容tpp.execute(),因为如果可以,则意味着 EDT 将被阻止,直到后台任务完成,并且后台任务将不再是后台任务。

但是,您可以做的是使用 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);
    }
于 2013-11-10T22:03:21.347 回答