讀書筆記:排序的執行器

handawei_5發表於2010-10-18
package v1ch14.ThreadPoolTest;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @version 2010-10-18 下午05:11:11
 * @author DaWei han
 * @EMAIL  handawei_1@126.com
 */
public class MyPoolTest {

	/**
	 * @param args
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//構造一個執行緒池
		ExecutorService executor=Executors.newCachedThreadPool();
		
		//構造一個順序的執行器
		ExecutorCompletionService<Integer> service=new ExecutorCompletionService<Integer>(executor);
		List<Callable<Integer>> taks=getTasks();
		
		for(Callable<Integer> call:taks)
		{
			//執行任務
			service.submit(call);
		}
		for(int i=0;i<taks.size();i++)
		{
			//獲得任務結果。它們是按結果的快慢排序的。
		    service.take().get(); 	
		}
      //上面的執行緒池順序服務是為了優化下面的執行緒池服務,因為下面的第一個任務可能很耗時,那麼後面的就必須等待。
		List<Future<Integer>> results= executor.invokeAll(taks);
		for(Future<Integer> result:results)
		{
			result.get();
		}
	}
 public static List<Callable<Integer>> getTasks()
 {
	 return null;
 }
}

 

相關文章