android中的线程使用与通信机制

1、android的所有应用程序组件,包括Activity、Service和BroadcastReceiver都在应用程序的主线程中执行,所有的耗时处理都可能阻塞其他组件,所以所有的耗时处理和IO操作都应该从主线程移到一个子线程中。常见的如:文件操作、网络查找、数据库事务和耗时复杂计算。
2、关于Android ANR,android系统规定,Activity对于一个输入事件(例如,按下一个按键)在5s的时间内没有响应,或者broadcast receiver在10s内没有完成对于onReceiver的处理。这是系统将认定为ANR,弹出提示框。
3、关于后台线程的几种方式:下面主要介绍下。

关于AsyncTask:
具体细节和使用方法了,详见android官方文档。http://developer.android.com/reference/android/os/AsyncTask.html
这里谈一下需要注意的事项:
每个AsyncTask实例只能被执行一次,如果试图第二次调用excute,则会抛出异常!
需要注意的是:当Activity重新启动时,操作将不会持续进行。AsyncTask在设备的方向变化而导致Activity被销毁和重新创建时会被取消。
AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor and FutureTask.
官方提示,至多几秒钟,需要长期运行的,建议使用java.util.concurrent包!

  • The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
  • AsyncTask类必须在UI线程被加载
  • The task instance must be created on the UI thread.
  • 类实例必须被在UI线程创建
  • execute(Params...) must be invoked on the UI thread.
  • execute方法必须在UI线程被调用
  • Do not   call onPreExecute()onPostExecute(Result)doInBackground(Params...)onProgressUpdate(Progress...) manually.
  • 不要显式调用这些方法
  • The task can be executed only once (an exception will be thrown if a second execution is attempted.)
  • 任务只能被执行一次,第二次被执行就会抛出异常。
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
自从android3.2版本开始,AsyncTask不再为每个AsyncTask的实例单独创建一个线程,相反,它使用一个excutor在单一的后台线程上运行所有的AsyncTask后台任务,这就意味着每个实例其实都是排队逐个运行的,显然,长时间运行的AsyncTask会阻塞其他的AsyncTask
这个让我感到非常困惑,这段话是developer上的官方文档,但是我去看了下源码,   明明是使用线程池的啊,   
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
当前的可用的核心数,由于很多移动设备会关闭无关核心以达到省电的目的,所以,可能大多数情况下都是1吧,只能暂时这么理解了。
public static final Executor THREAD_POOL_EXECUTOR new ThreadPoolExecutor(CORE_POOL_SIZEMAXIMUM_POOL_SIZE,KEEP_ALIVETimeUnit.SECONDSsPoolWorkQueuesThreadFactory);

深入研究了下源码,目前默认确实是单一后台线程执行的,源码如下:

private static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;
        //加锁保证了单次只能提交一个任务
        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                      public void run() {
                    try {
                       r.run();//防备提交的其中某个runnale方法造成异常阻塞其他提交
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }
            protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

从上面可以看出,虽然里面用了线程池,但使用加锁的机制,并且使用双向队列保证了串行提交(不一定是串行执行的,因为线程池会在提交之后立刻返回,但是如果线程池满,就要阻塞,这个机制的)。


关于Intent Service
IntentService是一个非常方便的包装类,具体实现细节详见官方。
http://developer.android.com/reference/android/app/IntentService.html
其他组件如果需要intentservice完成一个任务,需要启动Service,并传递一个包含完成任务所需参数的intent给它。
IntentService会将收到的所有请求intent放到队列中,并在异步后台线程中逐个去处理他们,当处理完所有收到的Intent之后,IntentService终止自己。
IntentService处理了几乎所有的复杂操作,比如,创建后台线程、将请求加入队列、UI线程同步。

关于Loader
Loader是一个抽象类,详见http://developer.android.com/guide/components/loaders.html
建议使用CursorLoader和AsyncTaskLoader,当然你也可是自己实现Loader,不过更建议实现AsyncTaskLoader。
CursorLoader是应该更具体的实现,用来实现异步查询Content Resolver并且返回一个cursor。

手动创建线程并实现和GUI同步

这种情况最复杂,涉及到诸多内容,如Hander、Message、Looper、MessageQueue所有android的消息传递机制,建议首先研究明白,具体可参见我的博客。
http://zjianjia.blog.163.com/blog/static/174089475201471510424366/

自己写了一个demo测试了下,源码放在我的github上,详见源码分析,欢迎指正。

https://github.com/yoson/androidThread


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章