国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android中實(shí)現(xiàn)Runnable接口簡(jiǎn)單例子

2020-04-11 11:49:23
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本課講的是如何實(shí)現(xiàn)一個(gè)Runnable,在一個(gè)獨(dú)立線程上運(yùn)行Runnable.run()方法.Runnable對(duì)象執(zhí)行特別操作有時(shí)叫作任務(wù)。
Thread和Runnable都是基礎(chǔ)的類,靠他們自己,能力有限。作為替代,Android有強(qiáng)大的基礎(chǔ)類,像HandlerThread,AsyncTask,IntentService。Thread和Runnable也是ThreadPoolExecutor的基礎(chǔ)類。這個(gè)類可以自動(dòng)管理線程和任務(wù)隊(duì)列,甚至可以并行執(zhí)行多線程。

定義一個(gè)實(shí)現(xiàn)Runnable接口的類

復(fù)制代碼 代碼如下:

public class PhotoDecodeRunnable implements Runnable {
    ...
    @Override
    public void run() {
        /*
         * Code you want to run on the thread goes here
         */
        ...
    }
    ...
}

實(shí)現(xiàn)run()方法

Runnable.run()方法包含了要執(zhí)行的代碼。通常,Runnable里可以放任何東西。記住,Runnable不會(huì)在UI運(yùn)行,所以不能直接修改UI對(duì)象屬性。與UI通訊,參考Communicate with the UI Thread
在run()方法的開(kāi)始,調(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)重要低,所以資源會(huì)優(yōu)先分配給其他線程(UI線程)
你應(yīng)該保存線程對(duì)象的引用,通過(guò)調(diào)用 Thread.currentThread()

復(fù)制代碼 代碼如下:

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());
        ...
    }
...
}

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 庐江县| 会泽县| 清远市| 太谷县| 苏尼特左旗| 清原| 巴彦淖尔市| 平湖市| 庆元县| 商水县| 屏山县| 自贡市| 郸城县| 邮箱| 毕节市| 揭东县| 宁化县| 大埔区| 青阳县| 伊金霍洛旗| 利津县| 巧家县| 大连市| 平顶山市| 东莞市| 丹东市| 锡林浩特市| 屏东市| 维西| 武威市| 微博| 晋州市| 亚东县| 甘肃省| 隆尧县| 荥经县| 古丈县| 志丹县| 格尔木市| 辛集市| 德江县|