简体   繁体   中英

Wait for a thread to finish before continuing the current thread?

So I have this in a method:

Runnable task = new PostLoadRunnable(tool, archive);
SwingUtilities.invokeLater(task);

But I want to make it so that the current method does not continue until the task thread has completed. I want to do something like join() but I can't work out how to do it. task.join() and Thread.task.join() doesn't work and Thread.currentThread().join() doesn't give me any options to join it to the thread that I want.

How do I stop the method until task is finished?

You don't want to do this at all. You state in comments that this code runs in the event dispatcher thread. You must not block this thread. Otherwise you will freeze the entire UI and the user will be most unhappy.

What you probably should do is disable the relevant parts of the UI until the task has completed. But without knowing your actual wider requirement it isn't possible to be sure.

You can accomplish this using a CountDownLatch . In your PostLoadRunnable run method you can have the following code in the finally section.

public void run() {
    try {
        ...
    } finally {
        latch.countDown();
    }
}

CountDownLatch latch = CountDownLatch(1);
Runnable task = new PostLoadRunnable(tool, archive, latch);
SwingUtilities.invokeLater(task);
latch.await();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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