簡體   English   中英

Thread.start() 和 Thread.run() 有什么區別?

[英]What is the difference between Thread.start() and Thread.run()?

為什么我們調用start()方法,而后者又調用run()方法?
我們不能直接調用run()嗎?

請舉例說明有什么不同。

不,你不能。 調用 run 將在同一個線程中執行run()方法,而不會啟動新線程。

為什么我們調用start()方法,而后者又調用run()方法?

不,那是不精確的。 start()反過來不會調用 run 方法。 相反,它啟動執行 run 方法的線程。 這是原生的。

我們不能直接調用run()嗎?

如果您直接調用run() ,則不會啟動線程,而只是在同一個調用方方法上執行該方法。

請舉例說明有什么不同。

網絡上有數百萬。 因此我不復制。

實際上thread.start()創建了一個新線程並有自己的執行場景。

但是thread.run()不會創建任何新線程,而是在當前運行的線程中執行 run 方法。

所以伙計們,如果你正在使用thread.run()然后想想如果你只想一個線程執行所有 run 方法,多線程有什么用。

因為 start() 不只是調用 run()。 它啟動一個新線程並在該線程中調用 run()。

主要區別在於,當程序調用start()方法時,會創建一個新線程,並在新線程中執行run()方法中的代碼。如果直接調用run()方法,則不會創建新線程,並且 run() 中的代碼將執行在當前線程上。

大多數情況下,調用 run() 是 bug 或編程錯誤,因為調用者有意調用 start() 來創建新線程,並且許多靜態代碼覆蓋工具(如 findbugs)可以檢測到此錯誤。 如果您想執行耗時的任務,請不要總是調用 start() 方法,否則如果直接調用 run() 方法,您的主線程將在執行耗時的任務時卡住。 在 Java 線程中 start 與 run 之間的另一個區別是您不能在線程對象上兩次調用 start() 方法。 一旦啟動,第二次調用 start() 將在 Java 中拋出 IllegalStateException 而您可以調用 run() 方法兩次。

如果您直接調用 run(),代碼將在調用線程中執行。 通過調用 start(),會創建一個新線程而不是主線程並並行執行。

你不能直接運行 run() 方法。 每當使用 thread.start() 啟動線程時,就會調用 run() 方法並執行進一步的操作。

因為start(); 同步並run(); 是簡單/常規的方法。 就像java知道從main();開始執行一樣main(); 方法。 由於線程知道從run();開始執行run();

這是來自Thread類的源代碼:

run(); 代碼:

@Override
public void run() { // overriding from Runnable
        if (target != null) {
            target.run();
        }
}

start(); 代碼:

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

簡而言之start(); 是線程的管理者,如何管理等等和run(); 是線程工作的起點。

這是 start 方法完成的工作

synchronized public void start()
{ 
    //it calls start0() method internally and start0() method does below
    //create a real child thread and register with thread scheduler
    //create runtime stack for child thread
    //call run() on underlying Runtime object
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM