天天看點

黑馬程式員:Callable和Future的用法

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TreadPool {


	public static void main(String[] args) {


		/**
		 * Callable和Future
		 * Future取得的結果類型和Callable傳回的結果類型必須一緻,通過泛型來實作
		 * Callable要采用ExecutorService的submit方法送出,傳回的future對象可以取消任務
		 * 
		 */
		
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<String> future = threadPool.submit(
				new Callable<String>() {
					@Override
					public String call() throws Exception {
						Thread.sleep(2000);
						return "hello";
					}
				}
		);
		try {
			//輸出future擷取到的threadPool的執行結果。
			//System.out.println(future.get());
			System.out.println(future.get(1,TimeUnit.SECONDS));//等待2秒,接收不到任務就抛異常了
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			throw new RuntimeException("等不急了");
		}
		
		/**
		 * 是個線程誰先完成就先接受誰的值
		 */
		
		ExecutorService threadPool = Executors.newFixedThreadPool(10);
		CompletionService<String> completionService = new ExecutorCompletionService<>(threadPool);
		for(int x=1; x<=10; x++){
			final int loop = x;
			completionService.submit(new Callable<String>(){
				@Override
				public String call() throws Exception {
					Thread.sleep(new Random().nextInt(5000));
					return "收到" + "線程" + loop ;
				}
			});
		}
		
		for(int y=1;y<=10;y++){
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	
	}


}