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. Spring分布式事务实现

    分布式事务是指操作多个数据库之间的事务,spring的org.springframework.transaction.jta.JtaTransactionManager,提供了分布式事务支持.如果使用 ...

  2. CXF之一 基础理论介绍

    WebService介绍   WebService让一个程序可以透明地调用互联网程序,不用管具体的实现细节.只要WebService公开了服务接口,远程客户端就可以调用服务.WebService是基于 ...

  3. 记录一下学习Android时遇到一些问题

    实在是不擅长Android开发,但在努力的学习当中.这篇文章就记录一下学习过程中,自己犯下的一些错误,同时也让自己记住别再犯同样的错误了.各位看官勿见笑! 一个关于空指针的错误 错误类型一: 未对对象 ...

  4. DataTable转List<Model>通用类【实体转换辅助类】

    /// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class Mo ...

  5. 【Windows核心编程】VirtualAlloc 例子

    // VirtualAlloc.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> #in ...

  6. bzoj 1061 [Noi2008]志愿者招募(数学模型,MCMF)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1061 [题意] 雇人满足每天至少需要的人数. [思路一] Byvoid的题解 clic ...

  7. PhoneGap,Cordova[3.5.0-0.2.6]:生成Android项目时出现错误(An error occurred while listing Android targets)

    我在升级到Cordova最新版本(3.5.0-0.2.6)后,在生成Android项目(cordova platform add android)时出现错误: Error: An error occu ...

  8. 单词计数WordCountApp.class

    public class WordCountApp { // 可以指定目录,目录下如果有二级目录的话,是不会执行的,只会执行一级目录. private static final String INPU ...

  9. sys.check_constraints

    每个用作 CHECK 约束(sys.objects.type = C)的对象都在表中占一行. SELECT name FROM sys.check_constraints -- equal to SE ...

  10. MATLAB / Simulink on BeagleBone Black

    转自:beagleboard@googlegroups.com邮件组 作者:kevind I have MATLAB / Simulink working with BeagleBone Black. ...