当前位置: 移动技术网 > IT编程>移动开发>Android > Android中实现Runnable接口简单例子

Android中实现Runnable接口简单例子

2019年07月24日  | 移动技术网IT编程  | 我要评论

情侣交换日记,带着武装去异世,9c8502

本课讲的是如何实现一个runnable,在一个独立线程上运行runnable.run()方法.runnable对象执行特别操作有时叫作任务。
thread和runnable都是基础的类,靠他们自己,能力有限。作为替代,android有强大的基础类,像handlerthread,asynctask,intentservice。thread和runnable也是threadpoolexecutor的基础类。这个类可以自动管理线程和任务队列,甚至可以并行执行多线程。

定义一个实现runnable接口的类

复制代码 代码如下:

public class photodecoderunnable implements runnable {
    ...
    @override
    public void run() {
        /*
         * code you want to run on the thread goes here
         */
        ...
    }
    ...
}

实现run()方法

runnable.run()方法包含了要执行的代码。通常,runnable里可以放任何东西。记住,runnable不会在ui运行,所以不能直接修改ui对象属性。与ui通讯,参考communicate with the ui thread
在run()方法的开始,调用 android.os.process.setthreadpriority(android.os.process.thread_priority_background);设置线程的权重,android.os.process.thread_priority_background比默认的权重要低,所以资源会优先分配给其他线程(ui线程)
你应该保存线程对象的引用,通过调用 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());
        ...
    }
...
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网