Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top