Home » Java programming language

Java Thread Class public void start() method with Example

Java Thread Class public void start() method: Here, we are going to learn about the public void start() method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 29, 2019

Thread Class public void start()

  • This method is available in package java.lang.Thread.start().
  • When we call start() method with thread object then it means the thread will start its execution.
  • start() method internally calls run() method of Runnable interface and to execute the code specified in the overridable run() method in our thread.
  • We can call start() method once for a particular thread in a program.
  • This method is not static so we cannot access this method with the class name too.
  • start() method of Thread class perform various task like First, it will create a new thread, Second the thread changes its state from Ready to Running state, Third, when target thread will get a chance to execute so its overridable run() will execute.
  • The return type of this method is void so it does not return anything.

Syntax:

    public void start(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the Thread.

Return value:

The return type of this method is void, it does not return anything.

Java program to demonstrate example of start() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/
import java.lang.Thread;

class MyThread extends Thread {
    // Override run() method of Thread class
    public void run() {
        System.out.println("Thread Name :" + Thread.currentThread().getName());
        System.out.println("We are in run() method of MyThread");
    }
}

class Main {
    public static void main(String[] args) {
        // Creating an object of MyThread and calling start() 
        // of Thread class and it calls run() method of MyThread 
        MyThread mt = new MyThread();
        mt.start();

        // Creating an object of MyThread and calling start() 
        // of Thread class and it calls run() method of Thread
        Thread t = new Thread();
        t.start();

        System.out.println("t.start() will call Thread class start() method with Thread object t");
    }
}

Output

E:\Programs>javac Main.java

E:\Programs>java Main
t.start() will call Thread class start() method with Thread object t
Thread Name :Thread-0
We are in run() method of MyThread


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.