线程启动的方法start()和run()

1.start
使用start方法才真正实现了多线程运行,因为使用start()方法不用等待run方法体代码执行完毕而直接继续执行下面的代码。
因为thread线程有5种状态,创建-就绪-运行-阻塞-死亡这五种,用Thread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,等到cpu空闲时,才会执行线程里面的run方法,run方法运行完毕,此线程结束。

2.run
因为run方法是thread里面的一个普通的方法,直接调用run方法,这个时候它是会运行在我们的主线程中的,程序中依然只有主线程这一个线程,其程序执行路径还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到写线程的目的。

代码示例:

public class ThreadDemo {
    public static void main(String[] args){
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());
        thread1.start();
        thread2.start();
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

两个线程都是使用start方法开启的,所以并不需要等待另一个完成,所以他们的执行顺序应该是并行的,我们运行看一下结果:
在这里插入图片描述
和我们分析的一样,那么我们改改代码,执行使用run方法,看看是否顺序执行

 public static void main(String[] args){
    Thread thread1 = new Thread(new MyRunnable());
    Thread thread2 = new Thread(new MyRunnable());
    thread1.run();
    thread2.run();
}

在这里插入图片描述
总结:调用start方法方可启动线程,而run方法只是thread的一个普通方法调用,还是在主线程里执行。

参考:https://my.oschina.net/134596/blog/1663837
https://blog.csdn.net/woshizisezise/article/details/79938915

发布了59 篇原创文章 · 获赞 15 · 访问量 559

猜你喜欢

转载自blog.csdn.net/qq_45287265/article/details/105054033