首頁 >Java >java教程 >為什麼「Thread.start()」對於 Java 中真正的多執行緒至關重要?

為什麼「Thread.start()」對於 Java 中真正的多執行緒至關重要?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 09:15:17355瀏覽

Why is `Thread.start()` essential for true multithreading in Java?

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():

  • Initializes a new thread and executes the run() method in a separate thread of execution.
  • Allocates system resources and sets up the thread's execution environment.
  • Control is transferred to the JVM to manage thread scheduling and execution.

Thread.run():

  • Directly invokes the run() method within the current thread.
  • Does not create a new thread; instead, it executes the code in the current thread of execution.
  • No system resources are allocated for thread management.

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn