AsyncTask原理

来源:互联网 发布:流行的骂人网络用语 编辑:程序博客网 时间:2024/06/08 15:41

AsyncTask的基原理是创建一个线程池,通过线程池执行一个Runnable对象(FutureTask),然后通过Handler通知UI线程。

1、线程池的创建。创建线程池,并返回一个执行器对象(Executor)

 

[java] viewplaincopy
  1. private static final int CORE_POOL_SIZE 5 
  2. private static final int MAXIMUM_POOL_SIZE 128 
  3. private static final int KEEP_ALIVE 10 
  4.   
  5. private static final BlockingQueue<Runnable> sWorkQueue  
  6.         new LinkedBlockingQueue<Runnable>(10);  
  7.   
  8. private static final ThreadFactory sThreadFactory new ThreadFactory()  
  9.     private final AtomicInteger mCount new AtomicInteger(1);  
  10.   
  11.     public Thread newThread(Runnable r)  
  12.         return new Thread(r, "AsyncTask #" mCount.getAndIncrement());  
  13.      
  14. };  
  15. style="color:#ff0000;"  </span>private static final ThreadPoolExecutor sExecutor new ThreadPoolExecutor(CORE_POOL_SIZE,  
  16.         MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);  

2、将被执行的Runnable对象(FutureTask)的创建。在构造方法中创建FutureTask。

 

 

[java] viewplaincopy
  1. public AsyncTask()  
  2.        mWorker new WorkerRunnable<Params, Result>()  
  3.            public Result call() throws Exception  
  4.                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  5.                return doInBackground(mParams);  
  6.             
  7.        };  
  8.   
  9.        mFuture new FutureTask<Result>(mWorker)  
  10.            @Override  
  11.            protected void done()  
  12.                Message message;  
  13.                Result result null 
  14.   
  15.                try  
  16.                    result get();  
  17.                catch (InterruptedException e)  
  18.                    android.util.Log.w(LOG_TAG, e);  
  19.                catch (ExecutionException e)  
  20.                    throw new RuntimeException("An error occured while executing doInBackground()" 
  21.                            e.getCause());  
  22.                catch (CancellationException e)  
  23.                   <span style="color:#ff0000;"</span>message sHandler.obtainMessage(MESSAGE_POST_CANCEL,  
  24.                            new AsyncTaskResult<Result>(AsyncTask.this(Result[]) null));  
  25.                    message.sendToTarget();  
  26.                    return 
  27.                catch (Throwable t)  
  28.                    throw new RuntimeException("An error occured while executing "  
  29.                            "doInBackground()"t);  
  30.                 
  31.   
  32.              <span style="background-color: rgb(255, 255, 255);" message sHandler.obtainMessage(MESSAGE_POST_RESULT,  
  33.                        new AsyncTaskResult<Result>(AsyncTask.thisresult));  
  34.                message.sendToTarget();</span>  
  35.             
  36.        };  
  37.     

 其中WorkRunnable是一个Callable对象:

 

 

[java] viewplaincopy
  1. private static abstract class WorkerRunnable<Params, Result> implements Callable<Result>  
  2.     Params[] mParams;  
  3.  

 

3、执行,execute方法。

 

[html] viewplaincopy
  1. public final AsyncTask<ParamsProgress, Result> execute(Params... params)  
  2.         if (mStatus != Status.PENDING)  
  3.             switch (mStatus)  
  4.                 case RUNNING:  
  5.                     throw new IllegalStateException("Cannot execute task:"  
  6.                             the task is already running.");  
  7.                 case FINISHED:  
  8.                     throw new IllegalStateException("Cannot execute task:"  
  9.                             the task has already been executed  
  10.                             "(a task can be executed only once)");  
  11.              
  12.          
  13.   
  14.         mStatus Status.RUNNING;  
  15.   
  16.         onPreExecute();  
  17.   
  18.         mWorker.mParams params 
  19.         sExecutor.execute(mFuture);  
  20.   
  21.         return this;  
  22.      

4、使用Handler通知UI线程,在上面的第二步中最后两行代码。