Multithreading captures exceptions in a thread

Source: Internet
Author: User
Tags thread class throwable

    1. Thread Class Best Practices:
      • When writing, it is best to set the thread name Thread.Name and set the thread group Threadgroup to facilitate management. In the event of a problem, the print line stacks (jstack-pid) can see at a glance which thread is out of the question, what the thread is doing.
    2. Two ways to implement
Method one thread way through thread group, thread name, and set Uncaughtexceptionhandler to catch exceptions
PublicStaticvoidMain (string[] args) {try{Thread t =new Thread (new Runnable () {@Override public void run () {int i = 10/0; System. out.println ( "run ...");}); T.setuncaughtexceptionhandler (new Uncaughtexceptionhandler () {@Override public void uncaughtexception (Thread T, Throwable e) {system. Out.println ( "catch to");}); T.start (); }catch (Exception e) {system. Out.println ( "catch Less")}}          

The output is as follows:
Catch up to the

public static void main(String[] args) {        try{ Thread t =new Thread(new Runnable(){ @Override public void run() { int i = 10/0; System.out.println("run...."); } }); t.start(); }catch(Exception e){ System.out.println("catch 不到"); } }

The output is as follows:

 Exception  In thread  "Thread-0" Java.lang com.credit.subject.traditional.run (Threadlocaltest.java:< Span class= "Hljs-number" >12) at Java.lang.run (Thread.java: 722) the thread cannot use handler to get the exception in the thread even if it does not catch the Try,catch. Need to use handler.  
Method two uses Executorservice to capture threads
   - 由于线程的本质特性,使得你不能捕获从线程中逃逸的异常。一旦异常逃出任务的run()方法它就会向外传播到控制台,除非你采取特殊的步骤捕获这种错误的异常。   - 在Java SE5之前,你可以使用线程组来捕捉这种异常,但是有了Java SE5,就可以用Executor来解决这个问题了。   - 下面的任务总是会抛出一个异常,该异常会传播到其run()方法的外部,并且main()展示了当你运行它时所发生的事情:
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ExceptionThread implements Runnable { public void run() { throw new RuntimeException(); } public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); service.execute(new ExceptionThread()); }}

The output is as follows:

ExceptionIn thread"Pool-1-thread-1" Java. lang. RuntimeException atCom. ABC. Thread. Exceptionthread.run (Exceptionthread.java: 6) at Java.util.runworker (threadpoolexecutor .java:1145) at Java.concurrent.run (threadpoolexecutor .java:615) at Java.run (Thread.java: 745)              

It is also not useful to place main body in the Try-catch statement block:

Import Java.util.concurrent.ExecutorService;Import java.util.concurrent.Executors;public class exceptionthread implements Runnable {public void run () {throw new runtimeexception ();} public static void main (string[] args) {try {executorservice service = Executors.newcachedthreadpool (); Service.execute (new Exceptionthread ());} catch (runtimeexception e) {System.out.println ( "catched Runtime Exception. ")}}              

This produces the same result as in the previous example: an uncaught exception.
-To solve this problem, we want to modify the way executor generates threads. Thread.uncaughtexceptionhandler is a new interface in Java SE5 that allows you to attach an exception handler on each thread object.
-Thread.UncaughtExceptionHandler.uncaughtException () is called when the thread is near death due to an uncaught exception. To use it, we created a new type of threadfactory that will attach a thread.uncaughtexceptionhandler to each newly created thread object.

Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.ThreadFactory;PublicClassExceptionThread2ImplementsRunnable {Publicvoid Run () {ThrowNew RuntimeException ("Nullpointer"); }PublicStaticvoid Main (string[] args) {Threadfactory tfactory =New Mythreadfactory (); Executorservice service = Executors.newcachedthreadpool (tfactory); Runnable task =New ExceptionThread2 (); Service.execute (Task); }}ClassMyuncaughtexceptionhandlerImplementsThread.Uncaughtexceptionhandler {Handles the exception thrown from the line thread.Publicvoid Uncaughtexception (Thread t, Throwable e) {System.out.println ("catched throwable:" + e.getclass (). Getsimplename () + "," + e.getmessage ());}} class Mythreadfactory implements threadfactory { //reorganize how threads are created public thread Newthread ( Runnable r) {Thread t = new Thread (R); //Bind an exception handler for each thread. T.setuncaughtexceptionhandler (new Myuncaughtexceptionhandler ()); System.out.println ("thread[" + t.getname () + "] created."); return t;}}             

The results of the implementation are as follows:

As you can see, there are 2 threads in the thread pool, and the exception is captured when a thread has an exception.

The

example above allows you to set the processor individually for each thread, using statements such as if, case, in the Newthread () method. If you know that you are going to use the same exception handler everywhere in your code, the easier way is to set a static domain in the thread class and set the processor as the default processor:

import Java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class settingdefaulthandler {public  Static void main (string[] args) {// Sets the default exception handler for the thread. Thread.setdefaultuncaughtexceptionhandler (new Myuncaughtexceptionhandler ()); Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (new ExceptionThread2 ())}}        

This processor is called only if there is no exception handler that is not caught by the thread. The system checks the thread-specific version, and if it is not found, checks whether the thread group has a proprietary Uncaughtexception () method and, if not, calls Defaultuncaughtexceptionhandler.

Reprint to: 54582646

Multithreading captures exceptions in a thread

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.