简体   繁体   English

等待一个线程完成,然后再继续当前线程吗?

[英]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. 我想做类似join()事情,但是我不知道怎么做。 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. task.join()Thread.task.join()不起作用,并且Thread.currentThread().join()没有给我任何选择将其连接到所需的线程。

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. 否则,您将冻结整个UI,并且用户将非常不满意。

What you probably should do is disable the relevant parts of the UI until the task has completed. 可能应该做的是禁用UI的相关部分,直到任务完成。 But without knowing your actual wider requirement it isn't possible to be sure. 但是,如果不知道您实际的更广泛的要求,就无法确定。

You can accomplish this using a CountDownLatch . 您可以使用CountDownLatch完成此操作。 In your PostLoadRunnable run method you can have the following code in the finally section. PostLoadRunnable运行方法中,您可以在finally部分中包含以下代码。

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

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

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

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