【发布时间】:2012-06-04 15:36:42
【问题描述】:
我写了一个 Java Daemon(一个实现 Daemon 和 Runnable 的类),现在我面临以下问题:
在 init() 中我创建了一个新线程。 Thread thread = new Thread(this);
在 start() 中,我启动了新线程。 thread.start()。
在运行中我做了很多不同的事情......然后发生异常。 (在我的例子中:NullPointerException。)。
现在发生的事情是我在 run() 中捕获了异常并调用了 stop()。在那里我调用thread.join(),但这永远不会结束并且不会抛出 InterruptedException。我该如何解决这个问题?
在 run() 中,我在 while 循环中做一些事情
private Thread thread;
public void init() {
// if init is successful: this.thread = new Thread(this);
// if init is not successful: call stop()
}
public void run() {
try{
// do something
while (!this.stopping)
{
// do somthing
}
} catch (Exception e) {
//do something and then call stop()
}
}
public void stop() {
this.stopping = true;
thread.join(); // catch InterruptedException if it did not work
// do some more things
}
这就是引发异常的地方。停止是不稳定的,一旦调用停止,我就将其设置为 true。
谢谢你:-)
我得到了很多答案,但我仍然没有解决这个问题。每个人都说我不应该在我的 run() 或 init() 方法中手动调用 stop()。我的问题是,当 init() 或 run() 中发生异常时,我真的想要 stop 程序。完成它,使程序不再运行。我不知道如何在不调用 stop() 的情况下实现这一点。简单地等到 run() 完成是行不通的,因为它会停止并且 stop() 永远不会被调用。我还不确定如何处理异常问题。
【问题讨论】:
-
你能多贴一点代码吗?事实上,我认为你应该尝试对 Callable docs.oracle.com/javase/6/docs/api/java/util/concurrent/… 和 ExecutorService 做同样的事情,因为你会在主线程中收到有关异常的通知。
-
那么我还能如何停止守护进程?
-
@nano7 -- 从
run()返回。 -
当 init() 被调用并且我在 init() 中做的一些事情失败时 - 我不应该在那里调用 stop() 吗?我应该抛出异常还是直接返回?
-
嗯。如果我不在 init() 中手动调用 stop(),如果 init() 失败,我将永远无法到达 stop(),因为如果 init() 失败,我不会创建新线程。我应该抛出 DaemonInitException 吗?
标签: java multithreading exception daemon runnable