使用线程池来实现AsyncTask的排队机制与拒绝策略

用imageview来实现海报墙,用ArrayBlockingQueue和ThreadPoolExecutor.DiscardOldestPolicy()来实现海报墙http请求的线程池的排队策略:
测试代码:
public class MyAsyncTask extends AsyncTask<String,Integer,String> {

private String TAG="MyAsyncTask";
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d(TAG, "doInBackground "+params[0]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

public class MainActivity extends Activity{

private ThreadPoolExecutor TestPool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_m);
testAysncTask();
}

void testAysncTask(){
TestPool = new ThreadPoolExecutor(3, 3, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy());

for (int i=0;i<50;i++){
MyAsyncTask task= new MyAsyncTask();
task.executeOnExecutor(TestPool, String.valueOf(i));
}
}
}


打印信息:
doInBackground 1 
doInBackground 0
doInBackground 2
doInBackground 47
doInBackground 48
doInBackground 49

将ThreadPoolExecutor的参数 corePoolSize和maximumPoolSize设置为3,表示线程池中保存和允许的最大线程数为3
第5个参数表示使用ArrayBlockingQueue队列来保存等待的线程,大小设为3,
第6个参数ThreadPoolExecutor.DiscardOldestPolicy()表示超出ArrayBlockingQueue队列的请求将被舍弃,舍弃的规则为保留最新的请求,因此看到打印最终执行的线程为0,1,2 和通过排队等待执行的最新的请求47,48,49

基本上用线程池的这种用法可以实现我们的处理大量http请求目的。

你可能感兴趣的:(拒绝策略,排队机制)