剑指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的一个普通方法的调用。
发布了242 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44240370/article/details/104103005