java并发编程笔记2----启动线程为什么用start()方法而不是run()方法

原课程B站地址:全面深入学习java并发编程,中级程序员进阶必会

众所周知,线程运行体运行的代码是重写Thread类的run()方法,而启动线程是使用start()方法,那为什么直接调用run()方法不行呢?

当调用start()方法启动线程的时候

public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("2 running");
            }
        };
        t1.start();
        log.debug("1 running");
    }
日志如下

可以看到,线程被正确启动,主线程main打印1 running,隔了2秒后t1线程打印 2 running。
在这里插入图片描述

当调用run()方法启动线程的时候

public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
            //改变一下位置,效果更明显一些
             	log.debug("2 running");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.run();
        log.debug("1 running");
    }
日志如下

可以看到,代码的执行全是由main线程来操作的,而且代码是串行执行,1 running等待 2 running执行完两秒才开始执行。由此可知,线程t1并没有被成功创建,这样做只是简简单单调用了一个方法。
在这里插入图片描述

结论

直接调用run()方法,会使得代码在主线程中执行,并没有开辟一个线程,只有调用start()方法,才能成功开辟一个新的线程。

发布了45 篇原创文章 · 获赞 113 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_41860619/article/details/105613489