gpt4 book ai didi

java - EDT、异步、同步

转载 作者:行者123 更新时间:2023-11-30 03:10:40 24 4
gpt4 key购买 nike

当从 EDT(事件调度线程)启动一个新线程时,新线程永远不会是 EDT,因为只有一个 EDT,对吗?我问,因为我看到一些代码检查 if (!SwingUtils.isDispatcherThread()),我想知道为什么它需要此检查?

我的问题是:当启动一个新线程时,是什么使它成为同步(必须等待新线程完成)或异步(新线程立即返回)?那么如何自己启动一个同步或异步线程呢?

使用以下示例。在 EDT 中启动非 EDT 线程时,如下所示:

public void actionPerformed(final ActionEvent e)
{
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
//do some non-gui task. The task is not long-running, but
//could be blocked
doTask();
}
};

new Thread(runnable).start();
}
});

从 EDT 生成的非 EDT 线程是同步还是异步?如果 doTask() 挂起,EDT UI 是否应该被阻止?

如果我无法控制 doTask() 并且该方法无法更改,那么有什么好方法来处理生成新线程并且新线程可能挂起的情况?在父线程中使用 Thread.join() ?

最佳答案

the new thread will never be EDT, as there is only one EDT, right?

对。

I am asking as I see some code checks "if (!SwingUtils.isDispatcherThread())", and I wonder why it needs this check?

因为有时,可以从 EDT 或后台线程调用方法,并且必须根据当前线程采取不同的操作。

when starting a new thread, what makes it synchronous (has to wait for the new thread to finish) or asynchronous (the new thread returns right away)?

当您启动一个新线程时,新线程始终与生成线程同时运行。除非您显式加入(或使用其他同步机制),否则生成线程永远不会等待生成的线程完成。

Should EDT UI be blocked if doTask() hangs?

不,除非生成的线程在保持 EDT 尝试获取的锁时挂起。

If I have no control over doTask() and the method cannot be changed, what is a good way to deal with the situation that spawns a new thread and the new thread might hang? use Thread.join() in parent thread?

情况会更糟:现在 EDT 也会挂起,从而完全卡住 UI,直到挂起的线程停止挂起并终止。

如果您有一个挂起的线程,请修复它正在执行的代码,以便它不再挂起。如果您无法修复它,请要求负责该代码的人员修复它。

关于java - EDT、异步、同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700872/

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