Translated From Google Android.

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 the PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
这句话可以将你的线程移动到后台。(该优先级低于主线程,避免与主线程竞争CPU)

管理多线程

这里以PhotoManager为例:

1.既然是个管理者,最好是单例:(至于如何创建单例,不解释了)

public class PhotoManager {
    ...
    static  {
        ...
        // Creates a single static instance of PhotoManager
        sInstance = new PhotoManager();
    }
   /**
     * Constructs the work queues and thread pools used to download
     * and decode images. Because the constructor is marked private,
     * it's unavailable to other classes, even in the same package.
     */
    private PhotoManager() {
    ...
    }
    ...

2.启动一个照片下载任务,通过线程池,从队列中取一个runnable也就是任务对象:

public class PhotoManager {
    ...
    // Called by the PhotoView to get a photo
    static public PhotoTask startDownload(
        PhotoView imageView,
        boolean cacheFlag) {
        ...
        // Adds a download task to the thread pool for execution
        sInstance.
                mDownloadThreadPool.
                execute(downloadTask.getHTTPDownloadRunnable());
        ...
    }

3.自定义Handler来更新UI

    private PhotoManager() {
    ...
        // Defines a Handler object that's attached to the UI thread
        mHandler = new Handler(Looper.getMainLooper()) {
            /*
             * handleMessage() defines the operations to perform when
             * the Handler receives a new Message to process.
             */
            @Override
            public void handleMessage(Message inputMessage) {
                ...
            }
        ...
        }
    }

4.决定线程池的参数:初始化的线程池大小和最大池大小

首先ThreadPoolExcutor是android定义的类,不是java.

那么线程池的大小如何决定?最大又该多少呢?

答:省事点:通过Runtime.getRuntime().availableProcessors()

public class PhotoManager {
...
    /*
     * Gets the number of available cores
     * (not always the same as the maximum number of cores)
     */
    private static int NUMBER_OF_CORES =
            Runtime.getRuntime().availableProcessors();
}

5.决定线程池的参数:空闲线程持续时间。(keep alive time),单位通过TimeUnit。

6.任务队列:可以使用LinkedBlockingQueue<Runnable>

public class PhotoManager {
    ...
    private PhotoManager() {
        ...
        // A queue of Runnables
        private final BlockingQueue<Runnable> mDecodeWorkQueue;
        ...
        // Instantiates the queue of Runnables as a LinkedBlockingQueue
        mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>();
        ...
    }
    ...
}

7.好,下面进入创建线程池:

private PhotoManager() {
        ...
   // Sets the amount of time an idle thread waits before terminating
   private static final int KEEP_ALIVE_TIME = 1;
   // Sets the Time Unit to seconds
   private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
   // Creates a thread pool manager
   mDecodeThreadPool = new ThreadPoolExecutor(
        NUMBER_OF_CORES,     // Initial pool size
        NUMBER_OF_CORES,    // Max pool size
        KEEP_ALIVE_TIME,
        KEEP_ALIVE_TIME_UNIT,
        mDecodeWorkQueue);
}

8.让线程池执行一个任务试试:ThreadPoolExecutor.execute()会将该任务加入到线程池的队列中。当一个空闲的线程变得可用时,Manager会将等待时间最长的任务运行在这个线程中。

public class PhotoManager {
    public void handleState(PhotoTask photoTask, int state) {
        switch (state) {
            // The task finished downloading the image
            case DOWNLOAD_COMPLETE:
            // Decodes the image
                mDecodeThreadPool.execute(
                        photoTask.getPhotoDecodeRunnable());
            ...
        }
        ...
    }
    ...
}

9.打断正在执行任务的某个或者所有线程

public class PhotoManager {
    public static void cancelAll() {
        /*
         * Creates an array of Runnables that's the same size as the
         * thread pool work queue
         */
        Runnable[] runnableArray = new Runnable[mDecodeWorkQueue.size()];
        // Populates the array with the Runnables in the queue
        mDecodeWorkQueue.toArray(runnableArray);
        // Stores the array length in order to iterate over the array
        int len = runnableArray.length;
        /*
         * Iterates over the array of Runnables and interrupts each one's Thread.
         */
        synchronized (sInstance) {
            // Iterates over the array of tasks
            for (int runnableIndex = 0; runnableIndex < len; runnableIndex++) {
                // Gets the current thread
                Thread thread = runnableArray[taskArrayIndex].mThread;
                // if the Thread exists, post an interrupt to it
                if (null != thread) {
                    thread.interrupt();
                }
            }
        }
    }
    ...
}

注意:大多数情况,Thread.interrupt()可以马上把线程打断掉。但是只能打断在等待的线程,不能打断CPU或者网络任务的线程。为了避免减缓或则锁住系统。你应该在尝试操作前,验证是否被打断。

/*
* Before continuing, checks to see that the Thread hasn't
* been interrupted
*/
if (Thread.interrupted()) {
    return;
}
...
// Decodes a byte array into a Bitmap (CPU-intensive)
BitmapFactory.decodeByteArray(
        imageBuffer, 0, imageBuffer.length, bitmapOptions);
...

Android线程和线程池的更多相关文章

  1. android中的线程池学习笔记

    阅读书籍: Android开发艺术探索 Android开发进阶从小工到专家 对线程池原理的简单理解: 创建多个线程并且进行管理,提交的任务会被线程池指派给其中的线程进行执行,通过线程池的统一调度和管理 ...

  2. Android开发之线程池使用总结

    线程池算是Android开发中非常常用的一个东西了,只要涉及到线程的地方,大多数情况下都会涉及到线程池.Android开发中线程池的使用和Java中线程池的使用基本一致.那么今天我想来总结一下Andr ...

  3. android线程与线程池-----线程池(二)《android开发艺术与探索》

    android 中的线程池 线程池的优点: 1 重用线程池中的线程,避免了线程的创建和销毁带来的性能开销 2 能有效的控制最大并发数,避免大量线程之间因为喜欢抢资源而导致阻塞 3 能够对线程进行简单的 ...

  4. 《Android开发艺术探索》读书笔记 (11) 第11章 Android的线程和线程池

    第11章 Android的线程和线程池 11.1 主线程和子线程 (1)在Java中默认情况下一个进程只有一个线程,也就是主线程,其他线程都是子线程,也叫工作线程.Android中的主线程主要处理和界 ...

  5. Android的线程和线程池

    ---恢复内容开始--- 一.Android线程的形态 (一)AsyncTask解析 AysncTask简介:①.实现上封装了Thread和Handler   ②.不适合进行特别耗时的后台任务 Ays ...

  6. 《Android开发艺术探索》第11章 Android的线程和线程池

    第11章 Android的线程和线程池 11.1 主线程和子线程 (1)在Java中默认情况下一个进程只有一个线程,也就是主线程,其他线程都是子线程,也叫工作线程.Android中的主线程主要处理和界 ...

  7. Android中线程和线程池

    我们知道线程是CPU调度的最小单位.在Android中主线程是不能够做耗时操作的,子线程是不能够更新UI的.在Android中,除了Thread外,扮演线程的角色有很多,如AsyncTask,Inte ...

  8. Android中的线程池概述

    线程池 Android里面,耗时的网络操作,都会开子线程,在程序里面直接开过多的线程会消耗过多的资源,在众多的开源框架中也总能看到线程池的踪影,所以线程池是必须要会把握的一个知识点; 线程运行机制 开 ...

  9. Android线程与线程池

    引言 在Android中,几乎完全采用了Java中的线程机制.线程是最小的调度单位,在很多情况下为了使APP更加流程地运行,我们不可能将很多事情都放在主线程上执行,这样会造成严重卡顿(ANR),那么这 ...

  10. android线程及线程池

    众所周知,在UI系统中进行一些耗时操作,都会导致卡顿现象,因为一次刷新在16ms,如果当次操作过了这个时间,那么用户就能感觉到明显的卡顿,甚至引起ANR . 对于这种情况,一般都是再起一个线程,进行一 ...

随机推荐

  1. Party at Hali-Bula

    题意: n个人参加party,给出n个人的工作关系树,一个人和他的顶头上司不能同时参加,party达到的最大人数并判断邀请的最大人数名单是否唯一. 分析: 树状dp入门 dp[i][f],以i为根的子 ...

  2. SQL Server缺省约束、列约束和表约束

    SQL Server缺省约束是SQL Server数据库中的一种约束,下面就为您介绍SQL Server缺省约束.列约束和表约束的定义方法啊,供您参考. SQL Server缺省约束 SQL Serv ...

  3. 使用jQuery Mobile实现通讯录

    jQuery Mobile 通讯录 拨打电话作者:方倍工作室 地址: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional/ ...

  4. 十字链表 Codeforces Round #367 E Working routine

    // 十字链表 Codeforces Round #367 E Working routine // 题意:给你一个矩阵,q次询问,每次交换两个子矩阵,问最后的矩阵 // 思路:暴力肯定不行.我们可以 ...

  5. hdfs[命令] dfs

    Usage: hadoop fs [generic options] [-appendToFile <localsrc> ... <dst>] [-cat [-ignoreCr ...

  6. [Hive - Tutorial] Type System 数据类型

    数据类型Type System Hive supports primitive and complex data types, as described below. See Hive Data Ty ...

  7. Google C++ 编程规范总结

    一.头文件 #define 的保护 项目 foo 中的头文件 foo/src/bar/baz.h 按如下方式保护: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ ...

  8. 将android Settings 源码 导入到 eclipse工程

    1.  新建 android 项目 拷贝源码/packages/apps/Settings到你的其它目录. 在eclipse中,新建项目,但是要从exitting source选择: 2. 导入相关的 ...

  9. 【现代程序设计】【homework-05】

    这次作业的运行效果图: 新建了20个客户端线程,服务器相应开了20个线程接收客户端数据,每一秒输出每一轮的结果 这次作业用c#完成 利用 Socket 类实现了局域网中的客户端和服务器之间的通信 主要 ...

  10. java中MessageDigest加密工具类

    import java.security.MessageDigest; public class EncryptionKit { public static String md5Encrypt(Str ...