java - CountDownLatch.await/countDown 与 Thread.join/interrupt 等待单个 Runnable

标签 java multithreading concurrency

要像java.awt.EventQueue.invokeLater/invokeAndWait一样实现invokeLater和invokeAndWait,我需要调用invokeLater并等待invokeAndWait中的可运行对象。

CountDownLatch.await/countDown 和 Thread.join/interrupt 似乎都可以工作,但哪个更好?有没有更简单的方法?

Thread.join/中断代码:

public interface EventQueue {
    /**
     * Executes a command in main thread.<p>
     * <b>Can be called outside main thread.</b>
     */
    public void invokeLater(Runnable runnable);

    /**
     * Executes and waits for a command in main thread.<p>
     * <b>MUST be called outside main thread.</b>
     */
    public default void invokeAndWait(Runnable runnable) {
        Thread thread = Thread.currentThread();
        invokeLater(() -> {
            runnable.run();
            thread.interrupt();
        });
        try {
            thread.join();
        } catch (InterruptedException e) {
            //
        }
    }
}

CountDownLatch.await/countDown 代码:

import java.util.concurrent.CountDownLatch;

public interface EventQueue {
    /**
     * Executes a command in main thread.<p>
     * <b>Can be called outside main thread.</b>
     */
    public void invokeLater(Runnable runnable);

    /**
     * Executes and waits for a command in main thread.<p>
     * <b>MUST be called outside main thread.</b>
     */
    public default void invokeAndWait(Runnable runnable) {
        CountDownLatch latch = new CountDownLatch(1);
        invokeLater(() -> {
            runnable.run();
            latch.countDown();
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

最佳答案

+1 表示 CountDownLatch。 它比 Thread 简单且轻量。

关于java - CountDownLatch.await/countDown 与 Thread.join/interrupt 等待单个 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27371211/

相关文章:

java - WebSphere AdminClient 连接到本地托管进程而不是 HOST :PORT specified in properties

c - 如何并行运行定时器任务?

java - 将本地新对象传递给线程,线程安全吗?

c++ - 共享内存 - 需要同步

java - 如何将一个 bean 注入(inject)另一个基于 getter 的 bean

java - 在 maven 插件中设置 tomcat 7 系统属性

c++ - 共享 vector 与原子 bool 同步

c# - .NET 4.0 System.Collections.Concurrent 集合在 .NET 3.0 SynchronizedCollection 的功能中添加了什么?

java - 如何检查单行输入中是否有两个相同的数字

c - 请解释这个结构的用法