1. 程式人生 > >【多執行緒系列】future模式

【多執行緒系列】future模式

package com.daojia.future;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
 * 
 * @author daojia
 *
 */
public class FutureTest {
	

	public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
		// TODO Auto-generated method stub

		useFuture();
		
	}

	 private static void useFuture() throws InterruptedException, ExecutionException, TimeoutException {  
	
	        ExecutorService exector = Executors.newFixedThreadPool(3);  
	        Future<Integer> futureA = (Future<Integer>) exector.submit(new Task("A1"));  
	        Future<Integer> futureB = (Future<Integer>) exector.submit(new Task("B1"));
	        System.out.println("a,b請求完成");
	           
	        int a=  futureA.get(1, TimeUnit.SECONDS);         
	         int b = futureB.get(1, TimeUnit.SECONDS); 	            
	     
	        exector.shutdown();  
	        System.out.println("所有任務執行完畢,res="+(a+b));
	    }  
	
}
class Task implements Callable<Integer>{
	 
	 private String name;
	 public Task(String name){
		 this.name = name;			 
	 }
	 
	    @Override
	    public Integer call() throws Exception {
	        System.out.println(System.currentTimeMillis()+" "+name+"run");
	        Random random = new Random();  
	        int num =  random.nextInt(100);
	        Thread.sleep(num);
	        System.out.println(System.currentTimeMillis()+" "+name+"runover,res="+num);
	        return num;
	    }
	}
模擬一個耗時的task,主執行緒負責彙總結果。,結果如下