In some scenarios, we often need to use multithreading to perform tasks to improve performance, but we know that the normal main thread is unable to handle the exception of the child thread, and once an exception occurs, it is propagated to the console. This time we need to deal with the exception in the thread, we can use executor to deal with.
A new Thread.uncaughtexceptionhandler interface is added to the Java5, which allows us to attach an exception handler on each thread object, with its unacughtexception () The method thread is called when it dies because of an uncaught exception.
First we implement the Thread.uncaughtexceptionhandler interface first:
Class Myuncaughtexceptionhandler implements thread.uncaughtexceptionhandler{//implements thread exception handling interface @Override public void Uncaughtexception (Thread t, Throwable e) { System. out. println ("cause" + e); }}
We are customizing a thread factory:
Class Handlerthreadfactory implements threadfactory{ @Override public Thread Newthread (Runnable r) { System. out. println (this+ "Create new Thread"); Thread t = new Thread (r); System. out. println ("create" +t); T.setuncaughtexceptionhandler (New Myuncaughtexceptionhandler ());//Set our own custom exception handling // Thread.setdefaultuncaughtexceptionhandler (); You can also use this method to set the default processor System. out. println ("eh=" +t.getuncaughtexceptionhandler ()); return t; }}
Finally we implement a runnable interface and throw an exception in the Run method:
Class MyThread implements Runnable { @Override public void Run () { Thread t = thread.currentthread ();
system. out. println ("Run ()" + t); System. out. println ("eh=" +t.getuncaughtexceptionhandler ()); throw new RuntimeException ();} }
OK, let's write a Main method to test some:
public static void Main (string[] args) { Executorservice exe = Executors.newcachedthreadpool (NEW Handlerthreadfactory ());//Use our custom threadfactory exe.execute (New MyThread ());}
The results of the operation are as follows:
[Email protected] new thread
Createthread[thread-0,5,main]
[Email protected]
Run () Thread[thread-0,5,main]
[Email protected]
[Email protected] new thread
Createthread[thread-1,5,main]
[Email protected]
Causejava.lang.RuntimeException
Obviously, the program can run, indicating that the exception was caught, and is the exception we throw, we hope to help you.
Digested in: 72989497
Java multi-thread captures exceptions in sub-threads---interview