In this chapter we will discuss the multi-threaded exception capture.
1. Exceptions to common conditions
Package Com.ray.ch17;public class Test {public static void main (string[] args) {try {new Threada (). Run ();} catch (Exceptio n e) {System.out.println ("catch to Exception");}}} Class Threada implements Runnable {@Overridepublic void run () {throw new RuntimeException ();}}
Output:
Snapping to exceptions
2. Multi-threaded exceptions
Package Com.ray.ch17;public class Test {public static void main (string[] args) {try {new Thread (new Threada ()). Start ();} C Atch (Exception e) {System.out.println ("catch to Exception");}}} 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. Question:
In the ordinary case, we can catch the exception smoothly, but if in multi-threaded case, the way to catch the exception is not the kind of the above
4. Solution
Implementing the Thread.uncaughtexceptionhandler Interface
(1) Use the ordinary way to achieve
Package Com.ray.ch17;public class Test {public static void main (string[] args) {try {thread thread = new Thread (new thread A ()); Thread.setuncaughtexceptionhandler (new Myuncaughtexceptionhandler ()); Thread.Start ();} catch (Exception e) {System.out.println ("catch to Exception");}}} 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 ("Snap To:" + t.getname () + "exception");}}
Output:
Snapping to: Thread-0 exceptions
(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 ()); Executorservice.execute (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 ("Snap To:" + t.getname () + "exception");}} Class Mythreadfactory implements Threadfactory {@Overridepublic thread newthread (Runnable r) {Thread thread = new Thread (r ); Thread.setuncaughtexceptionhandler (new Myuncaughtexceptionhandler ()); return thread;}}
Output:
Snapping to: Thread-0 exceptions
Summary: This section discusses the multi-threaded anomaly capture in detail.
This chapter is here, thank you.
-----------------------------------
Directory
Learn from the java-18.2 Basic threading mechanism (8) Multi-threaded exception capture