Java java.util.concurrent.Future的一個例子

package callableTest;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class CallableIndicator{
	private String name;
	private Double result;
	static public final int TIME = 3000;
	public CallableIndicator(String name, Double result){
		this.name = name;
		this.result = result;
	}
	
	public Double getResult(){
		return this.result;
	}
	
	public String getName(){
		return this.name;
	}
}

public class CallableTest {
	 private static final int POOL_SIZE = 2;
	 
	    static class CalcThread implements Callable<CallableIndicator> {
	    	
	    	private String name;
	        private List<Double> dataList = new ArrayList<>();
	 
	        public CalcThread(String name) {
	            for(int i = 0; i < 10000; ++i) {
	                dataList.add(Math.random());
	            }
	            this.name = name;
	            System.out.println("In CalcThread constructor, thread id: " + 
	            Thread.currentThread().getId());
	        }
	 
	        @Override
	        public CallableIndicator call() throws Exception {
	        	
	            double total = 0;
	            for(Double d : dataList) {
	                total += d;
	            }
	            
	            System.out.println("In CalcThread @Override call(), thread id: " + 
	    	            Thread.currentThread().getId());
	            Thread.sleep(CallableIndicator.TIME);
	            return new CallableIndicator(this.name, total / dataList.size());
	        }
	 
	    }
	 
	    public static void printThread(){
	    	System.out.println("In main Thread? " + Thread.currentThread().getId());
	    }
	    
	    public static void main(String[] args) {
	    	long start = System.currentTimeMillis();
	        List<Future<CallableIndicator>> fList = new ArrayList<>();
	        ExecutorService es = Executors.newFixedThreadPool(POOL_SIZE);
	        
	        printThread();
	        System.out.println("Ready to submit new thread...");
	        for(int i = 0; i < POOL_SIZE; ++i) {
	            fList.add(es.submit(new CalcThread("Jerry Thread: " + i)));
	        }
	 
	        for(Future<CallableIndicator> f : fList) {
	            try {
	            	/*
	            	 * 注意這個get是異步操作:The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. 
	            	 */
	                System.out.println("Thread name: " + f.get().getName() + " result: " +  f.get().getResult());
	                
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	        long end = System.currentTimeMillis();
	        System.out.println("duration: " + ( end - start));
	        es.shutdown();
	    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章