【问题标题】:Java "Fire and Forget" ThreadJava“一劳永逸”线程
【发布时间】:2011-12-09 12:10:26
【问题描述】:

我有办法

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

AnimationThread实现runnable的地方,它的构造函数是:

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

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

谢谢

【问题讨论】:

  • 你需要 start() 一个线程。调用run() 与任何其他方法一样,它在当前线程中运行,仅在完成时返回。

标签: java multithreading fire-and-forget


【解决方案1】:

你需要稍微移动一下:

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

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

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

【讨论】:

  • 请注意,在某些情况下,在构造函数中启动新线程可能会出现问题(有关详细信息,请参阅findbugs)。防止这种情况的一种简单方法是将 AnimationThread 类设为 final。
【解决方案2】:

也许您应该调用start 方法而不是run 方法。只有start 方法真正执行了一个新线程。

【讨论】:

  • 确实,尽管 AnimationThread 没有 start() 方法,尽管它的名称如此。
猜你喜欢
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2016-07-20
  • 2017-06-16
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多