gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:10:37 25 4
gpt4 key购买 nike

要像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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com