Java New Thread start() 与 run()的区别

来源:互联网 发布:上海网络通信设备公司 编辑:程序博客网 时间:2024/06/07 02:02

考虑下面两个代码片段:

代码1:

{    @Override    public void run()    {        //background task?    }}).run();

代码2:

{    @Override    public void run()    {        //background task?    }}).start();

代码1中使用了run()来执行runnable里面的代码。根据Thread的文档,这里实际上没有另开线程执行操作,runnable里面的代码会运行在当前线程,所以如果代码1是在主线程调用而且runnable里面有耗时操作的话就会阻塞主线程造成ANR。

代码2与代码1的区别是使用start()来执行runnable里面的代码,从Thread的文档可知start()会启动一个新的线程来执行代码。因此,如果有耗时代码的话记得用Thread.start()来操作。

———— start

public synchronized void start ()Added in API level 1Starts the new Thread of execution. The run() method of the receiver will be called by the receiver Thread itself (and not the Thread calling start()).

———— run

public void run ()Added in API level 1Calls the run() method of the Runnable object the receiver holds. If no Runnable is set, does nothing.

可以看出,run()仅仅是把thread的runnable对象的run()调用了一次。

0 0