
android 2.3之后,真正的Android团队在Async任务中做了什么更改.当我执行以下代码时,在AndroID 2.3和3.0中都得到相同的结果.
package com.sample.asynctask;import androID.app.Activity;import androID.os.AsyncTask;import androID.os.Bundle;import androID.util.Log;public class AsyncTaskTestActivity extends Activity { private static final String TAG = "AsyncTaskTestActivity"; /** Called when the activity is first created. */ @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.main); //ExecutorService executorService = Executors.newFixedThreadPool(1); for (int i = 1; i <= 20; i++) { TestTask testTask = new TestTask(i); testTask.execute(); } } private static class TestTask extends AsyncTask<VoID, Integer, VoID> { int i; public TestTask(int i) { Log.i(TAG, "Constructor for " + i); this.i = i; } @OverrIDe protected voID onPreExecute() { // Todo auto-generated method stub super.onPreExecute(); Log.i(TAG, "onPreExecute for " + i); } @OverrIDe protected VoID doInBackground(VoID... params) { Log.i(TAG, i + " Thread goes to sleep"); try { Thread.sleep(20000); } catch (InterruptedException e) { // Todo auto-generated catch block e.printstacktrace(); } Log.i(TAG, i + " Thread wakes up"); return null; } @OverrIDe protected voID onPostExecute(VoID result) { // Todo auto-generated method stub super.onPostExecute(result); Log.i(TAG, "onPostExecute for " + i); } }}我在Gingerbread中的假设:5异步任务一次在一个线程池中执行.
我在Honeycomb中的假设是:1异步任务一次在一个线程池中执行.就像并发执行一样.
但是,Gingerbread和Honeycomb都同时执行5个Async任务.
而且,当Async任务的数量增加到140.i时,我也没有得到java.util.concurrent.RejectedExecutionException.
我的假设是否正确?里面到底发生了什么?
解决方法:
我的假设是否正确?
您的假设是正确的.
里面到底发生了什么?
android.os.AsyncTask内部的默认执行程序:
... ...private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;... ...已在android.app.ActivityThread中重置:
... ...// If the app is Honeycomb MR1 or earlIEr, switch its AsyncTask// implementation to use the pool executor. normally, we use the// serialized executor as the default. This has to happen in the// main thread so the main looper is set right.if (data.appInfo.targetSdkVersion <= androID.os.Build.VERSION_CODES.HONEYCOMB_MR1) { AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POol_EXECUTOR);}... ...AndroID Gingerbread之后,异步任务实际上发生了什么变化?
请查看AsyncTask change history,更具体地说,这是一个:
Mar 17, 2011 – AsyncTask now uses the poll executor for apps up through HC MR1 and t…
当异步任务的数量增加到140时,我没有得到java.util.concurrent.RejectedExecutionException.
这是任务总数和每个任务执行时间的一个因素,在另一个世界中,任务总数为140(大于128),但是,在任何给定时间由线程池分配的线程总数较小而不是128,换句话说,您的情况下总是有一些空闲线程(由于上一个任务已完成并释放了资源).您可以尝试增加每个任务的执行时间,例如Thread.sleep(10000),这可能会给您RejectedExecutionException.
总结以上是内存溢出为你收集整理的java-Android Gingerbread之后,异步任务中真正发生了什么变化?全部内容,希望文章能够帮你解决java-Android Gingerbread之后,异步任务中真正发生了什么变化?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)