1. 程式人生 > >使用執行緒池來實現AsyncTask的排隊機制與拒絕策略

使用執行緒池來實現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請求目的。