Thread Main

In this chapter you will learn:

  1. What is the main Java thread

Main Java 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();/*from   j ava2  s.  c o  m*/
    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");
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to make a thread sleep
  2. Pause the execution utilities
  3. Add a delay for each loop
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor