剑指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的一个普通方法的调用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章