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

发布于 2024-09-13 09:28:27 字数 1081 浏览 0 评论 0原文

我需要运行两个 SwingWorker。其中一个只能在另一个完成后才能运行。我可以像这样运行它们吗?

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();
    }
}

我应该如何取消它们?像这样?

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

多谢!

I need to run two SwingWorkers. 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

音盲 2024-09-20 09:28:27

你可以这样做并且它会起作用。但是,除非您未显示外部 done 中的其他操作,否则最好使用在 doInBackground 中执行这两个操作并返回数组的操作结果。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文