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

考虑下面两个代码片段:

代码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 1
Starts 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 1
Calls the run() method of the Runnable object the receiver holds. If no Runnable is set, does nothing.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值