Android中的线程与线程池

Android沿用了Java的线程模型。Android提供的异步处理任务方式有如下几种。
1.异步请求类AsyncTask
2.串行处理顺利HandlerThread类
3.IntentService服务

查看源码,它提供了三个泛型参数Params,Progress,Result。

public abstract class AsyncTask<Params, Progress, Result> {

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();


public AsyncTask(@Nullable Looper callbackLooper) {

        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

 mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };

}

//内部类
 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
}

FutureTask类源码

public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
/*
Executors
public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
*/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,432评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,246评论 4 61
  • 大家好,第30次语音60秒。 xdite老师在前天的公众号上分享了一个速读的方法,总结如下: 写下问题。每次读书前...
    bluealon阅读 699评论 5 10
  • 每件事好像都是有成本的! 听完今天课脑袋里立马就浮现200块!我就在想怎么让她(他)把这200交了! 觉得好像和之...
    小雪A阅读 160评论 0 0
  • 2017年3月13日 晴天 大家好,我是日记星球171号星宝宝吴敏,我正在参加日记星球轻而易举写作富足写...
    纯爱香颂安安阅读 782评论 0 1