What is the Thread.start() function in Java?
The Thread.start() method from java.lang.Thread class is used to start thread execution. It implicitly calls the Thread.run() method to execute a newly created thread.
Syntax
public void start()
Parameters
NA: it does not take any argument.
Return value
Its return type is void, so it does not return anything.
IllegalThreadStateException: This exception will be raised whenstart()is called more than once.
Example 1
In the code snippet below, the start() method will execute the run() method from the Runnable interface and print some text:
// including Thread classimport java.lang.Thread;// Main classpublic class MainThread extends Thread implements Runnable {public static void main(String args[]) {MainThread thread = new MainThread();// --- start() method ---thread.start();}// overriding thread run method@Overridepublic void run() {System.out.println("I'm from run() method..");System.out.println("Thread executing...");}}
Explanation
- Line 2: We import the
Threadclass. - Line 6: We create a thread.
- Line 8: We call the
start()method. - Lines 11 to 15: We override the
run()method.
Example 2
In the code snippet below, the start() method throws an IllegalThreadStateException exception when we call the start() method more than once:
// including Thread classimport java.lang.Thread;// Main classpublic class MainThread extends Thread implements Runnable {public static void main(String args[]) {MainThread thread = new MainThread();// --- start() method ---thread.start();thread.start();}// overriding thread run method@Overridepublic void run() {System.out.println("I'm from run() method..");System.out.println("Thread executing...");}}
Explanation
- Line 2: We import the
Threadclass. - Line 6: We create a thread.
- Lines 8 and 9: We call the
start()method twice. - Lines 12 to 16: We override the
run()method.