简体   繁体   English

线程崩溃时究竟会发生什么?

[英]What exactly happens when a thread crashes?

I am a little confused on what happens when there is an uncaught exception. 我对未捕获的异常会发生什么感到困惑。 For example: 例如:

public class TestActivity extends Activity {
  private Fish fish;

  void onCreate(Bundle savedInstanceState) {
    new Thread(new Runnable() {
        fish.swim();
    }).start();
  }
}

The code above crashes the app when executed even if its on a different thread since fish was never initialized and a NPE happens. 上面的代码即使在不同的线程上执行,也会使应用程序在执行时崩溃,因为fish从未被初始化并且NPE发生了。 However: 然而:

public class TestActivity extends Activity {
  private Fish fish;

  void onCreate(Bundle savedInstanceState) {
    ScheduledExecutorService executorService =     
  Executors.newScheduledThreadPool(10);
            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    fish.swim();

                }
            }, 0, TimeUnit.SECONDS);
  }
}

The code above doesn't crash the app even though it produces a NullPointerException, is it because it is in a different thread pool? 上面的代码即使生成NullPointerException也不会使应用程序崩溃,是因为它位于不同的线程池中吗? Does that mean if I have a threadpool with 10 different threads running, does the whole threadpool crash and the 9 other threads will die? 这是否意味着如果我有一个正在运行10个不同线程的线程池,整个线程池会崩溃并且其他9个线程会死掉吗?

I am a bit confused because I previously thought that when a thread crashes, only that thread dies and the threadpool it was living in is unaffected. 我有点困惑,因为我以前认为,当线程崩溃时,只有那个线程死亡,并且它所在的线程池不受影响。 Can someone explain this to me please? 有人可以向我解释一下吗?

From the of docs ThreadPoolExecutor : 来自docs ThreadPoolExecutor

Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. 注意:如果将动作显式地或通过诸如Submit之类的方法包含在任务(例如FutureTask)中,则这些任务对象会捕获并维护计算异常,因此它们不会导致突然终止,并且内部异常不会传递给此方法。

The reason why the code does not crash your app is because the exception is silently handled for you. 代码不会使您的应用程序崩溃的原因是,异常是为您静默处理的。 Also, when the submitted task encounters an exception, its further executions are silently suppressed. 另外,当提交的任务遇到异常时,其进一步执行将被静默抑制。

In case of a scheduled thread pool, the value that you pass determines the number of threads that can be scheduled concurrently. 如果是调度线程池,则传递的值确定可以同时调度的线程数。 So, you will have just 1 thread in the pool. 因此,池中只有1个线程。 This is in contrast with the fixed thread pool which will maintain the said number of threads in the pool even if a few of them crash. 这与固定线程池相反,固定线程池即使在其中一些线程崩溃的情况下,也将保持池中的线程数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM