run()和start()的区别

205 阅读2分钟

run()和start()的区别

什么是run()方法?

​ run()方法只是类的一个普通方法.

​ 如果直接调用run()方法,程序中依然只有主线程这一个线程,其程序执行路径还是只有一条,还是要顺序执行,还是要等待run()方法执行完毕后才可以继续执行下面的代码.

public class template{
    public static void main(String[] args){
        Thread thread = new Thread(new myThread);
        thread.run();
        System.out.println("finish");
    }
}
class myThread implements Runable{
    @Override
    public void run(){
        System.out.println("myThread run start");
        try{
            Thread.sleep(5*1000);//等待5秒
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("myThread run end");
    }
}

​ 运行结果:

myThread run start
myThread run end
finish

什么是start()方法?

​ 用start方法来执行线程,是真正实现了多线程.

​ 通过调用Tread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法.

​ 但要注意的是,此时无需等待run()方法执行完毕,即可继续执行下面的代码.

public class template{
    public static void main(String[] args){
        Thread thread = new Thread(new myThread);
        thread.start();
        System.out.println("finish");
    }
}
class myThread implements Runable{
    @Override
    public void run(){
        System.out.println("myThread run start");
        try{
            Thread.sleep(5*1000);//等待5秒
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("myThread run end");
    }
}

​ 运行结果:

finish
myThread run start
myThread run end

启动线程是否可以直接调用run()方法?

image-20220824092328286.png

​ 如果直接调用线程类的run()方法,这会被当做一个普通的函数调用,程序中仍然只有主线程这一个线程,也就是说,start()方法能够异步地调用run()方法,但是直接调用run()方法确实同步的,因此,也就无法达到多线程的目的.

区别

  1. Run仅仅是执行了里面的代码逻辑,并没有新开一个线程

    start是新开了一个线程,然后在新的线程里面执行里面的逻辑

  2. 当一个线程启动后,不能重复调用start(),否则会报IllegalStateException异常.

    但是可以重复调用run()方法.

总结

1. start方法用来启动相应的线程
1. run方法只是thread的一个普通方法,在主线程里执行
1. 需要并行处理的代码放在run方法中,start方法启动线程后自动调用run方法
1. run方法必须是public的访问权限,返回类型为