t.start():- The
start()method is used to initiate a new thread. - It creates a separate call stack for the new thread and invokes the
run()method in that new thread. - Invoking
start()on a thread calls therun()method implicitly. Example:
- The
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Executes `run()` in a new thread
}
}
t.run():- The
run()method is called directly, just like a normal method call. - It does not create a new thread; the
run()method executes in the current thread’s call stack. Example:
MyThread t = new MyThread(); t.run(); // Executes `run()` in the main thread, no new thread created- The
Tasks of start() Method
- Allocates memory and resources for the new thread.
- Registers the thread with the operating system.
- Calls the
run()method in the new thread.
**Overriding run() and **start()
- Can We Override
run()?:- Yes, overriding
run()is the primary way to define the behavior of a thread. - The
run()method contains the code to be executed by the thread. Example:
- Yes, overriding
class CustomThread extends Thread {
@Override
public void run() {
System.out.println("Custom thread logic here.");
}
}
- Can We Override
start()?:- Technically, yes, but it is not recommended.
- Overriding
start()will prevent the thread from functioning correctly unless the overridden method callssuper.start(). Example:
class CustomThread extends Thread {
@Override
public void start() {
System.out.println("Start method overridden.");
super.start();
}
@Override
public void run() {
System.out.println("Thread logic running.");
}
}
Warning: Overriding start() without calling super.start() will cause the thread to execute like a normal method and not in a new thread.
Can a Thread Be Restarted?
- No, a thread cannot be restarted once it has completed execution.
- Once a thread finishes its
run()method and enters the terminated state, callingstart()on the same thread instance will throw anIllegalThreadStateException. Example:
Thread t = new Thread(() -> System.out.println("Thread running"));
t.start();
t.start(); // Throws IllegalThreadStateException
Solution: To restart the same logic, you need to create a new thread instance.
Thread t1 = new Thread(() -> System.out.println("Thread running"));
t1.start();
Thread t2 = new Thread(() -> System.out.println("Thread running again"));
t2.start();
Summary
- Use
start()to initiate a new thread and execute therun()method in a separate thread. - Calling
run()directly does not create a new thread; it executes in the current thread. - You can override
run()to define thread behavior, but overridingstart()is generally discouraged. - Threads cannot be restarted once they have terminated.