![]() |
VOOZH | about |
In Java's multithreading concept, start() and run() are the two important methods of the Thread class. Although they might seem similar, they behave very differently. This article explains the differences and shows how to use them effectively.
The start() method is used to begin a new thread of execution. It performs two main tasks:
Thread running using start()
Explanation: Calling start() creates a new thread. run() is executed in the context of that new thread.
The run() method contains the code executed by the thread. However, calling run() directly does not create a new thread. Instead, it behaves like a normal method call executed in the current thread.
Thread running using run()
Explanation: Here, run() is executed in the main thread, so no multithreading occurs.
In Java's Multi-Threading Concept, another most important difference between start() and run() method is that we can't call the start() method twice otherwise it will throw an IllegalThreadStateException whereas run() method can be called multiple times as it is just a normal method calling.
Example 1: Multiple invocation of start() method.
Output:
Current thread: Thread-0
Exception in thread "main" java.lang.IllegalThreadStateException
Example 2: Multiple invocation of run() method
Current thread: main Current thread: main
Explanation: As we can see in the above example, calling run() method twice doesn't raise any exception and it is executed twice as expected but on the main thread itself.
| Feature | start() Method | run() Method |
|---|---|---|
| Thread Creation | Creates a new thread. | Does not create a new thread. |
| Execution Context | Runs run() in a separate thread. | Runs run() in the current thread. |
| Purpose | To start concurrent execution. | To define the code that a thread will execute. |
| Behavior | Allows true parallel execution. | Acts like a normal method call. |
| Usage Example | t1.start(); | t1.run(); |