Java:守护进程:thread.join() 未完成,之前在一个线程中抛出异常

标签 java multithreading exception daemon runnable

我编写了一个Java Daemon(一个实现Daemon和Runnable的类),现在我面临以下问题:

在 init() 中我创建了一个新线程。 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() 的情况下实现这一目标。简单地等待 run() 完成是行不通的,因为它会停止,而 stop() 永远不会被调用。我还不确定如何处理异常问题。

最佳答案

调用stop 就可以了。人们警告您不要调用 Thread.stop(),但您并没有这样做。您正在所做的是在您想要加入的同一线程上调用join - 这当然会导致死锁。你有

catch (Exception e) {
  //do something and then call stop()
}

这意味着您确实从run方法调用stop。那是错误的。它毫无异常(exception)地工作,因为那时你没有进入 catch block 。您只需在该 catch block 中编写 break; 即可中断 while 循环。

顺便说一句,您根本不需要对 Thread 的引用——这只是令人困惑的事情。如果您需要访问正在执行 run 方法的 Thread 实例,只需调用 Thread.currentThread() 即可。

关于Java:守护进程:thread.join() 未完成,之前在一个线程中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815646/

相关文章:

java - 将 JSF inputText 的内容写入文件

java - maven插件组件注入(inject)null

ios - 意外的核心数据多线程违规

asp.net-mvc - ASP.NET MVC 和 Ajax 中的异常处理 - [HandleException] 过滤器

java - 接口(interface)的方法应该抛出异常吗?

c# - WebAPI 过滤器的 ActionExecutedContext 中的异常属性为 null

java - 如何更新和增加 postgresql 和 mybatis 中的计数器

java - 如何获取管道兼容的jenkins SimpleBuildStep插件中的环境参数?

Java boolean 表达式并发行为

c# - 跨线程读取值不重要的变量