考虑下面两个代码片段:
代码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()调用了一次。
本文深入探讨了Java线程执行中的两种方式:使用run()直接执行Runnable任务与使用start()启动新线程执行任务的区别。重点解释了两者在实际应用中的优劣及如何避免主线程阻塞导致的ANR问题。
2128

被折叠的 条评论
为什么被折叠?



