Calling Thread.start() vs Thread.run() in Java
Introduction:
In Java, multithreading provides a mechanism for concurrent execution of tasks. One of the key components of multithreading is the Thread class. To execute a thread, one can either call Thread.start() or Thread.run(). This article aims to clarify the differences between these two methods and demonstrate when it makes a difference.
Understanding the Difference:
Calling Thread.start() on a thread object initiates a new thread of execution. This instructs the operating system's thread scheduler to create a new thread and schedule its execution. Once started, the thread becomes independent and executes concurrently with the main thread.
On the other hand, calling Thread.run() on a thread object simply executes the run() method of the thread in the current thread. In this case, the thread is not scheduled to run independently, and the run() method is executed sequentially after the run() method is invoked.
Why Start a Thread Instead of Calling Run?
Starting a thread has several benefits over directly calling run():
Example Demonstrating the Difference:
To illustrate the difference, consider the following example:
public class ThreadExample extends Thread { @Override public void run() { System.out.println("Thread is running..."); } public static void main(String[] args) { ThreadExample thread = new ThreadExample(); // Call the run() method directly - executed in the main thread thread.run(); // Start the thread - runs concurrently with the main thread thread.start(); } }
When this code is executed with the run() method call, the output will be:
Thread is running...
In this case, the run() method executes in the main thread, and there is no concurrency. However, when the code is executed with the start() method call, the output will be:
Thread is running...
... followed by the output of the main thread, indicating that the thread is running concurrently.
The above is the detailed content of What is the difference between calling Thread.start() and Thread.run() in Java?. For more information, please follow other related articles on the PHP Chinese website!