劍指Offer(線程)——線程start和run方法的區別

先從一個簡單的程序看起:
使用start():

public class ThreadTest {

    private static void attack(){
        System.out.println("fight");
        System.out.println("current thread is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                attack();
            }
        };
        System.out.println("current main thread is:" + Thread.currentThread().getName());
		thread.start();
    }
}

可以看出線程被切換了不是主線程去執行非main的方法。
在這裏插入圖片描述

使用run()方法:

public class ThreadTest {

    private static void attack(){
        System.out.println("fight");
        System.out.println("current thread is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                attack();
            }
        };
        System.out.println("current main thread is:" + Thread.currentThread().getName());
        thread.run();
    }
}

輸出結果爲:
在這裏插入圖片描述
從結果可以看出不管是主線程還是其他的線程方法,在run方法下執行的線程都是用主線程去執行。

原理如下:
在這裏插入圖片描述

  1. 調用start()方法會創建一個新的子線程並啓動;
  2. run()方法只是Thread的一個普通方法的調用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章