Android中實現(xiàn)Runnable接口簡單例子
本課講的是如何實現(xiàn)一個Runnable,在一個獨立線程上運行Runnable.run()方法.Runnable對象執(zhí)行特別操作有時叫作任務(wù)。
Thread和Runnable都是基礎(chǔ)的類,靠他們自己,能力有限。作為替代,Android有強大的基礎(chǔ)類,像HandlerThread,AsyncTask,IntentService。Thread和Runnable也是ThreadPoolExecutor的基礎(chǔ)類。這個類可以自動管理線程和任務(wù)隊列,甚至可以并行執(zhí)行多線程。
定義一個實現(xiàn)Runnable接口的類
public class PhotoDecodeRunnable implements Runnable {
...
@Override
public void run() {
/*
* Code you want to run on the thread goes here
*/
...
}
...
}
實現(xiàn)run()方法
Runnable.run()方法包含了要執(zhí)行的代碼。通常,Runnable里可以放任何東西。記住,Runnable不會在UI運行,所以不能直接修改UI對象屬性。與UI通訊,參考Communicate with the UI Thread
在run()方法的開始,調(diào)用 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);設(shè)置線程的權(quán)重,android.os.Process.THREAD_PRIORITY_BACKGROUND比默認(rèn)的權(quán)重要低,所以資源會優(yōu)先分配給其他線程(UI線程)
你應(yīng)該保存線程對象的引用,通過調(diào)用 Thread.currentThread()
class PhotoDecodeRunnable implements Runnable {
...
/*
* Defines the code to run for this task.
*/
@Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
...
/*
* Stores the current Thread in the PhotoTask instance,
* so that the instance
* can interrupt the Thread.
*/
mPhotoTask.setImageDecodeThread(Thread.currentThread());
...
}
...
}
相關(guān)文章
Android使用內(nèi)置WebView打開TextView超鏈接的實現(xiàn)方法
這篇文章主要介紹了Android使用內(nèi)置WebView打開TextView超鏈接的實現(xiàn)方法,文中給出了詳細(xì)的示例代碼,對各位Android開發(fā)者們具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03android教程之使用popupwindow創(chuàng)建菜單示例
這篇文章主要介紹了android使用popupwindow創(chuàng)建菜單的示例,需要的朋友可以參考下2014-02-02Android開發(fā)仿bilibili刷新按鈕的實現(xiàn)代碼
這篇文章主要介紹了Android 仿bilibili刷新按鈕的實現(xiàn)代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-10-10Android實現(xiàn)聯(lián)動下拉框二級地市聯(lián)動下拉框功能
這篇文章主要介紹了Android實現(xiàn)聯(lián)動下拉框二級地市聯(lián)動下拉框功能,本文給大家分享思路步驟,給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-12-12