Java线程停止没有异常

标签 java multithreading

当我为我的程序使用 4 个线程时通常没有问题,但今天我将它增加到 8 个并且我注意到 1-3 个线程停止工作而没有抛出任何异常。无论如何要找出他们为什么停下来?有没有办法让线程重新启动?

我的线程结构是这样的

public void run()
{
  Main.logger.info(threadName + ": New Thread started (inside run)");
  while (true)
  {
    try
    {
      //all my code
      //all my code
      //all my code
    }
    catch(Exception e)
    {
      Main.logger.error("Exception: " + e);
      try
      {
        Thread.sleep(10000);
      }
      catch (InterruptedException e1)
      {
        e1.printStackTrace();
      }
    }
    finally
    {               
      try
      {
        webClient.closeAllWindows();
        Thread.sleep(3000); 
        Main.logger.info(threadName + ": Closed browser!");
      }
      catch (Exception e)
      {
        Main.logger.error("Exception: " + e);
      }
    }  
  }// end while
}

问候!

最佳答案

请注意 Error 不是 Exception ;这是一个Throwable .
因此,如果您捕获异常错误 仍会通过:

private void m() {    
    try {
        m(); // recursively calling m() will throw a StackOverflowError
    } catch (Exception e) {
        // this block won't get executed, 
        // because StackOverflowError is not an Exception!
    }
}

要捕获“一切”,请将您的代码更改为:

try {
    ...
} catch (Throwable e) {
   // this block will execute when anything "bad" happens
}


请注意,如果发生错误,您可能无能为力。错误的 javadoc 摘录:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

关于Java线程停止没有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11927248/

相关文章:

c - 多线程和缓存非同时使用内存

c# - 多线程访问MapPoint?

ios - GCD 的核心数据

java - 使用线程池/线程来读取大文本文件?

java - java的compareTo()函数中字符的层次结构

java - 使用 url redirect 更改部分 url

java - 如何使用 RestTemplate 为每个请求设置 RequestConfiguration?

Java Swing 文本字段和按钮的边框

java - 如何使用 pdfbox 将 unicode 文本写入 pdf?

java - 如何使用 HTMLUnit 确定页面更改?