Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Main Thread in java

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 436
    Comment on it

    Main Thread:

    When we run a Java program  then main thread begins running immediately. It is created automatically. The main thread is the first as well as last thread in a java program to end.

    It is the main thread from which other child threads will be created.

    Example:

    // the main Thread. 
    public class MainThread {
      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");
        }
      }
    }

     

    Output:

    Current thread: Thread[main,5,main]
    After name change: Thread[My Thread,5,main]
    
    5
    4
    3
    2
    1

    We can control main thread by using  thread object. Thread object will hold the reference of the main thread with the help of currentThread() method of  Thread class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: