0%

Android开发:多线程操作-指定代码运行在一个线程上

本课讲的是如何实现一个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());
        ...
    }
...
}