CountDownLatch.await / countDown vs Thread.join / interrupt等待单个Runnable

时间:2014-12-09 03:59:33

标签: java multithreading concurrency

要实现invokeLater和invokeAndWait,比如java.awt.EventQueue.invokeLater / invokeAndWait,我需要调用invokeLater并等待invokeAndWait中的runnable。

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 个答案:

答案 0 :(得分:2)

+1 CountDownLatch。 它比Thread更简单,重量更轻。