Handler.postDelayed(new Runnable)是否運行在主線程

知識點
postDelayed(new Runnable())是否運行在主線程中?
答案 是的。
這個 new Runnable() 依附於創建Handler的線程,
代碼如下
在絕對的UI線程中打印線程ID:

System.out.println("UI Thread = " + Thread.currentThread().getId());  

下面在posdelayed中打印運行線程的ID:

new Handler().postDelayed(new Runnable() {  
    @Override  
    public void run() {  
        System.out.println("Handler Thread = " + Thread.currentThread().getId());  
        ImageUtil.deleteImageFromSDCard(imgPath);  
    }  
}, 3000);  

最後打印如下:

07-09 10:47:24.110 17026-17026/com.spd.sinoss I/System.out: UI Thread = 1  
07-09 10:47:27.111 17026-17026/com.spd.sinoss I/System.out: Handler Thread = 1  

可以看出來,它們兩個程序都是運行在主線程中的。
方法的官方解釋是:

The runnable will be run on the thread to which this handler is attached.

既是說,這個開啓的runnable會在這個handler所依附線程中運行,而這個handler是在UI線程中創建的,所以
自然地依附在主線程中了。

postDelayed(new Runnable()) 而沒有重新生成新的 New Thread()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章