In Java, threads enable concurrent execution of multiple tasks within a program. They help improve performance and responsiveness in applications.
- Threads can be created by extending the Thread class or implementing the Runnable interface, both requiring the run() method.
- Use the start() method to begin execution, as it internally calls run() and creates a new thread.
start() Method
The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM. The main purpose of the start() method is to create a separate call stack for a new thread. When start() is invoked:
- JVM creates a new thread.
- A separate call stack is allocated for that thread.
- The JVM internally calls the run() method.
Because of this, multiple threads can execute simultaneously.
Example: Java code to see that all threads are pushed on same stack if we use run() instead of start().
class ThreadTest extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Main
{
public static void main(String[] args)
{
int n = 8;
for (int i=0; i<n; i++)
{
ThreadTest object = new ThreadTest();
// start() is replaced with run() for
// seeing the purpose of start
object.run();
}
}
}
Output:Â
Â
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Explanation:
- The class
ThreadTestextends the Thread and overrides therun()method. - In the
main()method, multiple objects ofThreadTestare created in a loop. - The program calls run() directly instead of start().
- Because run() is called directly, no new threads are created.
- All executions run in the same main thread, so the same thread ID is printed each time.