Java Thread Tutorial - Java Current Thread








A statement can be executed by different threads at different time.

The Thread class static method currentThread() returns the reference of the Thread object that calls this method.

Consider the following statement:

Thread  t = Thread.currentThread();

The statement will assign the reference of the thread object that executes the above statement to the variable t.

Example

The following code demonstrates the use of the currentThread() method.

Two different threads call the Thread.currentThread() method inside the run() method of the CurrentThread class.

The program simply prints the name of the thread that is executing.

public class Main extends Thread {
  public Main(String name) {
    super(name);// www . jav a  2s. c  o  m
  }

  @Override
  public void run() {
    Thread t = Thread.currentThread();
    String threadName = t.getName();
    System.out.println("Inside run() method:  " + threadName);
  }

  public static void main(String[] args) {
    Main ct1 = new Main("First Thread");
    Main ct2 = new Main("Second Thread");
    ct1.start();
    ct2.start();

    Thread t = Thread.currentThread();
    String threadName = t.getName();
    System.out.println("Inside  main() method:  " + threadName);
  }
}

The code above generates the following result.

When you run a class, the JVM starts a thread named main, which is responsible for executing the main() method.





Handling an Uncaught Exception in a Thread

We can handle an uncaught exception thrown in a thread.

It is handled using an object of a class that implements the java.lang.Thread.UncaughtExceptionHandler interface.

The interface is defined as a nested static interface in the Thread class.

The following code shows a class which can be used as an uncaught exception handler for a thread.

class CatchAllThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
  public void uncaughtException(Thread t, Throwable e) {
    System.out.println("Caught  Exception from  Thread:" + t.getName());
  }/*from  w  w w  .  java2 s  .  c o  m*/
}

public class Main {
  public static void main(String[] args) {
    CatchAllThreadExceptionHandler handler = new CatchAllThreadExceptionHandler();

    // Set an uncaught exception handler for main thread
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    // Throw an exception
    throw new RuntimeException();
  }
}

The code above generates the following result.