The Main Thread

When a Java program starts up the main thread begins running immediately. You can obtain a reference to main thread by calling the method currentThread().

Its general form is shown here:


static Thread currentThread( )

static Thread currentThread( ) returns a reference to the thread in which it is called.


// Controlling the main Thread. 
public class Main {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    System.out.println("Current thread: " + t);
    // change the name of the thread
    t.setName("My Thread");
    System.out.println("After name change: " + t);
    try {
      for (int n = 5; n > 0; n--) {
        System.out.println(n);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted");
    }
  }
}
Home 
  Java Book 
    Thread Conncurrent  

Thread:
  1. Multithreaded Programming
  2. The Main Thread
  3. Thread Name
  4. Thread sleep
  5. Thread Creation
  6. isAlive( ) and join( )
  7. Thread Priorities
  8. Thread Synchronization
  9. Interthread Communication
  10. Suspending, Resuming, and Stopping Threads
  11. Handle Uncaught Exception
  12. ThreadLocal variables