Java "Fire and Forget"线程

标签 java multithreading fire-and-forget

我有一个方法

public static void startAnimation() {
    new AnimationThread().run();
}

其中AnimationThread实现了runnable,它的构造函数是:

public AnimationThread() {
    new Thread(this, "Animation Thread");
    EventQueue.setAnimationCounter(0);
    alive = true;
}

我从小程序的 init() 方法调用的方法挂起,因为它从不返回值。有没有办法启动这个线程并完成 init() 方法,以便我的小程序启动!

谢谢

最佳答案

你需要稍微移动一下东西:

public AnimationThread() {
   EventQueue.setAnimationCounter(0);
   alive = true;
   new Thread(this, "Animation Thread").start();
}

public static void startAnimation() {
   new AnimationThread();
}

start() 是神奇的 Thread 方法,它在不同的线程上运行代码; AnimationThread 构造函数调用后会正常返回,AnimationThread.run() 将在新线程中执行。

关于Java "Fire and Forget"线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445306/

相关文章:

java - 如何定义AWT菜单中菜单项的顺序?

java - Gson:预期为 begin_array,但为 STRING 如何控制它

c++ - C++中的多个超时

Python 创建一个线程并在按下按键时启动它

java - 使用 java.util.concurrent 触发并忘记

java - 为什么 Grails 需要 Xerces?

java - Spring MockMvc - 请求参数列表

multithreading - 等待共享计时器的多个 go 例程导致竞争

c# - C# 中的 Fire and Forget Sql Server 存储过程

WCF 客户端导致服务器挂起直到连接故障