Java Multi-thread multithreading exception capture _java

Source: Internet
Author: User

  One: Why should we talk about the abnormal capture of multithreading alone?

Let's take a look at an example:

The public class ThreadException implements runnable{@Override the public
  Void Run () {
    throw new RuntimeException ( );
  }
  Behavior: the console prints exception information and runs for a period of time before stopping public
  static void Main (string[] args) {
    //Even putting the execution statement of the thread into the Try-catch block is useless
    try {
      Executorservice exec = Executors.newcachedthreadpool ();
      Exec.execute (New ThreadException ());
    } catch (RuntimeException e) {
      System.out.println ("Exception has been handled!");}}

A Run-time exception is manually thrown in run, a thread is started in main, the exception is caught in a catch statement block, and a word is snapped. The results of the operation are shown below:

The exception was found thrown to the console and no statements in the catch block were printed.

Conclusion: Multithreading cannot handle exceptions as they are caught in sequential execution, and exceptions are thrown directly to the console (because of the nature of threads, you cannot capture exceptions that escape from threads). Once the exception escapes from the task's Run method, it propagates outwards to the console unless you catch the exception in a special form. , this can make you very headache, unable to catch the exception can not handle the problem caused by the exception.

So, how do we think of catching exceptions in multiple threads?

Catching exceptions in multiple threads

Let's follow the following steps to complete this experiment:

  1. Define exception handler

requirements, the implementation of the Thread.uncaughtexceptionhandler Uncaughtexception method, as follows:


 * * First step: Define "Exception handler" conforming to the specification of the thread exception handler
 * Implement Thread.uncaughtexceptionhandler Specification * *
class Myuncaughtexceptionhandler implements thread.uncaughtexceptionhandler{
   * * Thread.UncaughtExceptionHandler.uncaughtException () is called when the thread is near death due to an unhandled exception ()
   *
  @Override public
  Void Uncaughtexception (Thread T, Throwable e) {
    System.out.println ("Caught  " +e);
  }

 2. Define the thread factory that uses the exception handler


 * * Second step: Define the Thread factory
 * The thread factory is used to attach the task to the thread and bind the thread to an exception handler/
class Hanlderthreadfactory implements threadfactory{
  @Override public
  Thread Newthread (Runnable r) {
    System.out.println (this+ "Creating new Thread ");
    Thread t = new Thread (r);
    System.out.println ("created" +t);
    T.setuncaughtexceptionhandler (New Myuncaughtexceptionhandler ())//Set the exception handler for the Thread factory
    System.out.println ("eh=" + T.getuncaughtexceptionhandler ());
    return t;
  }
}

  3. Define a task so that it throws an exception


 * * Third step: Our task may throw
 an exception * display throws a exception * * *
class Exceptionthread implements runnable{
  @ Override public
  Void Run () {
    Thread t = thread.currentthread ();
    System.out.println ("Run () by" +t);
    System.out.println ("Eh =" +t.getuncaughtexceptionhandler ());
    throw new RuntimeException ();
  }

  4. Call the experiment


 /* Fourth step: Create a thread pool using the threading factory and call its Execute method/public
class threadexceptionuncaughtexceptionhandler{
  public static void Main (string[] args) {
    Executorservice exec = Executors.newcachedthreadpool (new Hanlderthreadfactory ());
    Exec.execute (New Exceptionthread ());
  }

The results of the operation are shown below:

Third, the conclusion

To capture the exceptions generated by multithreading in Java, you need to customize the exception handler and set it to the corresponding thread factory (that is, step one and step two).

Four, expand

If you know that you're going to use the same exception handler everywhere in your code, it's easier to set up a static domain in the thread class and set this processor as the default, not captured processor.

This processor is invoked only if there is no thread-specific exception handler that is not caught.

public static void Main (string[] args) {
    Thread.setdefaultuncaughtexceptionhandler (new Myuncaughtexceptionhandler ());
    Executorservice exec =executors.newcachedthreadpool ();
    Exec.execute (New Exceptionthread ());
}

The above is the entire contents of this article for the Java multi-line thread of the exception capture, this article if there is wrong place to understand, welcome criticism correction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.