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: Calling run() directly executes the method in the main thread, so no new thread is created and the same thread ID is printed every time. Since there is no multithreading, all 8 executions run sequentially in a single call stack.