Java-18.2 basic thread mechanism (8) multi-thread exception capture
In this section, we will discuss how to capture exceptions in multiple threads.
1. Exceptions in general situations
Package com. ray. ch17; public class Test {public static void main (String [] args) {try {new ThreadA (). run ();} catch (Exception e) {System. out. println ("caught exceptions") ;}} class ThreadA implements Runnable {@ Overridepublic void run () {throw new RuntimeException ();}}
Output:
Caught exceptions
2. multithreading exceptions
Package com. ray. ch17; public class Test {public static void main (String [] args) {try {new Thread (new ThreadA ()). start ();} catch (Exception e) {System. out. println ("caught exceptions") ;}} class ThreadA implements Runnable {@ Overridepublic void run () {throw new RuntimeException ();}}
Output:
Exception in thread "Thread-0" java. lang. RuntimeException
At com. ray. ch17.ThreadA. run (Test. java: 18)
At java. lang. Thread. run (Thread. java: 662)
3. Problem:
Under normal circumstances, we can capture exceptions smoothly. However, in the case of multiple threads, the exception capture method is not the one above.
4. Solution
Implement the Thread. UncaughtExceptionHandler Interface
(1) using common methods
Package com. ray. ch17; public class Test {public static void main (String [] args) {try {Thread thread = new Thread (new ThreadA (); thread. setUncaughtExceptionHandler (new MyUncaughtExceptionHandler (); thread. start ();} catch (Exception e) {System. out. println ("caught exceptions") ;}} class ThreadA implements Runnable {@ Overridepublic void run () {throw new RuntimeException () ;}} class MyUncaughtExceptionHandler implements Thread. uncaughtExceptionHandler {@ Overridepublic void uncaughtException (Thread t, Throwable e) {System. out. println ("captured:" + t. getName () + "exception ");}}
Output:
Caught: Thread-0 exception
(2) Use the thread pool to implement
Package com. ray. ch17; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. threadFactory; public class Test {public static void main (String [] args) {ExecutorService executorService = Executors. newCachedThreadPool (new mythreadfactory(new ThreadA (); executorservice.exe cute (new ThreadA (); executorService. shutdown () ;}} class ThreadA implements Runnable {@ Overridepublic void run () {throw new RuntimeException () ;}} class MyUncaughtExceptionHandler implements Thread. uncaughtExceptionHandler {@ Overridepublic void uncaughtException (Thread t, Throwable e) {System. out. println ("captured:" + t. getName () + "exception");} class MyThreadFactory implements ThreadFactory {@ Overridepublic Thread newThread (Runnable r) {Thread thread = new Thread (r); thread. setUncaughtExceptionHandler (new MyUncaughtExceptionHandler (); return thread ;}}
Output:
Caught: Thread-0 exception
Summary: This chapter discusses in detail the exception capture of multiple threads.
This chapter is here. Thank you.