Create and set UncaughtExceptionHandler before starting new thread to catch unexpected runtime exception in Multithreading application. package demo; public class ExceptionHandler { public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { throw new RuntimeException("Critical Error"); } }); System.out.println("Starting new thread " + Thread.currentThread().getName()); //Throw this exception if any exception has occurred inside running thread but was not caught anywhere else //This should be set before starting the new thread thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { System.out.println("Error occurred on thread: " + thread.getName() + ". Reason :
Setting the custom name for Thread in Java. Printing the Thread running sequence. package demo ; public class Main { public static void main ( String [] args ) throws InterruptedException { Thread thread1 = new Thread ( new Runnable () { @Override public void run () { //execute after getting instruction from OS System . out .println ( "Inside and running thread " + Thread . currentThread () .getName ()) ; System . out .println ( "Current priority " + Thread . currentThread () .getPriority ()) ; } }) ; thread1 .setName ( "Custom Worker Thread" ) ; thread1 .setPriority ( Thread . MAX_PRIORITY ) ; System . out .println ( "We are in thread " + Thread . currentThread () .getName () + " before new thead" ) ; thread1 .start () ; //start the thread and inform the OS System . out .println ( "We are