简体   繁体   English

我可以在另一个SwingWorker中运行吗?

[英]Can I run one SwingWorker within another?

I need to run two SwingWorker s. 我需要运行两个SwingWorker One of them can only run after the other is done. 其中一个只能在另一个完成后才能运行。 Can I run them like this? 我可以这样运行它们吗?

class TestWorker {
    private FirstWorker worker1;
    private SecondWorker worker2;

    public TestWorker() {
        worker1 = new FirstWorker() {
            @Override
            protected void done() {
                try {
                    result1 = get();
                } catch (Exception) {
                    // exception handling
                }

                worker2 = new SecondWorker() {
                    @Override
                    protected void done() {
                        try {
                            result2 = get();
                        } catch (Exception) {
                            // exception handling
                        }
                    }
                }

                worker2.execute();
            }
        }

        worker1.execute();
    }
}

And how should I cancel them? 我应该如何取消呢? Like this? 像这样?

private cancel() {
    if (worker2 != null) work2.cancel();
    if (worker1 != null) work1.cancel();
}

Thanks a lot! 非常感谢!

You can do it that way and it will work. 您可以那样做,它将起作用。 However, unless there are other operations in your outer done that you're not showing, you would probably be better off with something that did both operations in doInBackground and returned an array of the results. 不过,除非是在你外的其他操作done ,你不显示,你很可能会用的东西,在做了两个操作更好doInBackground并返回结果的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM