多線程start()與run()的區別


概要


 

1.start()與run()介紹

2.start()與run()源碼查看

3.start()與run()測試

 

start()與run()介紹

1.通過我們在啟動線程的時候使用的start,為什么不用run呢? 因為start()會新開一個線程來執行;而run只是一個普通想法,相當於當前線程來調用,不會啟動新線程;

2.start()只能調用一次,run()可以調用多次

 

start()與run()源碼查看

1.先來看下start()的源碼,start()啟動線程其實是通過start0()啟動的

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();  //調用本地方法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 */
            }
        }
    }

    private native void start0(); //本地方法start0()

 

2.run()源碼

public void run() {
        if (target != null) {
            target.run();
        }
    }

只是調用了runnable里面的run方法,並沒有創建新的線程

 

start()與run()測試

理論也看了,源碼也看了,線程來實踐一下是不是這樣的

public class StartRun {

    public static void main(String[] args){

        Thread test=new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println(Thread.currentThread().getName());
            }
        });
        test.run();

    }
}
對應的輸出結果為main,即主線程,並沒有創建新的線程
public class StartRun {

    public static void main(String[] args){

        Thread test=new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println(Thread.currentThread().getName());
            }
        });
        test.start();

    }
}

對應的輸出結果為Thread-0,創建了新的線程

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM