If the following classes are defined in Java, you want to catch exceptions in a multithreaded environment
Static Class Myrun implements Runnable {
@Override public
void Run () {
System.out.println ("Myrun.run ()"); C4/>throw new RuntimeException ();
}
You cannot catch an exception in a program that calls these two threads in the following two ways.
try {
new Thread (New Myrun ()). Start ();
\ catch (Exception e) {
//Todo:handle Exception
System.out.println ("Caught exception in Main");
}
try {
Executors.newcachedthreadpool (). Execute (New Myrun ());
} catch (Exception e) {
//Todo:handle Exception
System.out.println ("Caught exception in Main");
}
In Java, if you want to catch an exception in a thread, you need to implement it by Uncaughtexceptionhandler.
Uncaughtexceptionhandler is an interface with only one method:
void Uncaughtexception (Thread t, Throwable e)
This method is invoked when a given thread terminates because of a given catch exception.
So, if you want to catch the thread's exception, we can implement Uncaughtexceptionhandler:
Static Class Myuncaughtexceprionhandler implements Uncaughtexceptionhandler {
@Override public
Void Uncaughtexception (Thread T, Throwable e) {
//TODO auto-generated method stub
System.out.println (" Caughtexception in my handler ");
System.out.println (e);
}
Then, before the thread starts, set the Uncaughtexceptionhandler of the Threads:
Thread thread = new Thread (new Myrun ());
Thread.setuncaughtexceptionhandler (New Myuncaughtexceprionhandler ());
Thread.Start ();
However, when using the thread pool, the problem is where to set the Uncaughtexceptionhandler.
At this point, you need to customize a new threadfactory:
Static Class Handlerthreadfactory implements Threadfactory {
@Override public
Thread Newthread (Runnable r) {
thread t = new Thread (r);
T.setuncaughtexceptionhandler (New Myuncaughtexceprionhandler ());
return t;
}
}
Then run the program in the following ways:
Executorservice exe = executors.newcachedthreadpool (new
handlerthreadfactory ());
Exe.execute (New Myrun ());