Understanding the Distinction between Thread.start() and Thread.run()
When working with multithreading in Java, programmers encounter two key methods: Thread.start() and Thread.run(). While their names may suggest similar functionality, they serve distinctly different purposes.
What Do These Methods Do?
Thread.start():
Thread.run():
Why Can't We Just Call Thread.run()?
If Thread.run() also executes the run() method, why can't we simply call this instead of Thread.start()? The reason lies in the isolation and independent execution that multithreading provides.
Calling Thread.run() executes the code in the current thread, not in a separate thread. This means that any code in the run() method still interacts with and affects resources in the current thread. This is not the intended purpose of multithreading, which allows for concurrent execution of tasks.
Example Illustrating the Difference:
Consider the following code:
public class ThreadExample { public static void main(String[] args) { Thread t1 = new Thread(() -> System.out.println("Thread 1")); Thread t2 = new Thread(() -> System.out.println("Thread 2")); // Here, we call Thread.start() and Thread.run(): t1.start(); // Starts Thread 1 in a separate thread t2.run(); // Executes Thread 2 in the current thread System.out.println("Main Thread"); } }
Output:
Thread 1 Main Thread
Calling Thread.start() on t1 creates a new thread and executes the run() method in that thread, allowing it to print "Thread 1." On the other hand, calling Thread.run() on t2 executes the run() method in the current (i.e., main) thread, bypassing the creation of a new thread. This results in "Thread 2" not being printed, as it is never executed in a separate thread.
以上是為什麼「Thread.start()」對於 Java 中真正的多執行緒至關重要?的詳細內容。更多資訊請關注PHP中文網其他相關文章!