Android中创建多线程管理器实例

2019-12-10 20:01:34王振洲

调用线程池类里的方法来开始任务

线程池类里定义一个方法,用来添加任务到线程池队列,如:

复制代码
public class PhotoManager {
    ...
    // 供PhotoView调用获取图片
    static public PhotoTask startDownload(
        PhotoView imageView,
        boolean cacheFlag) {
        ...
        // 添加一个任务到线程池
        sInstance.
                mDownloadThreadPool.
                execute(downloadTask.getHTTPDownloadRunnable());
        ...
    }

 

实例化一个UI线程的Handler.

Handler用于与UI线程通讯,大多数UI控件只允许在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) {
                ...
            }
        ...
        }
    }

 

判断线程池参数

一旦你有了全部类结构,你就可以开始定义线程池。实例化一个线程池对象,你需要下面的值:
初始池大小,最大池大小。
线程池的线程数量主要依赖于设备的CPU核心数.可以从系统环境中获取。