Java多線程與併發應用-(8)-Callable和Future

demo1: 使用FutureTask和Callable,獲取一個線程的返回值。在獲取返回值前可以做其他事,在Future.get()時阻塞,也可調用

get(long timeout, TimeUnit unit)方法設置在等待long時間後如果還沒有返回值拋出異常。

package com.lipeng;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureAndCallable1 {

	/**
	 * 使用FutureTask和Callable
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		//FutureTask實現了Runnalbe接口,所以可以用來構造Thread.
		//FutureTask實現了Callable接口,可以通過get獲取線程返回值
		FutureTask<String> futureTask=new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "hello";
			}
		});
		new Thread(futureTask).start();
		System.out.println("線程開始。。。。。。");
		//doSomeThing
		System.out.println(futureTask.get());
	}

}

demo2:使用ExecutorService的submit(Callable c)方法

package com.lipeng;

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

public class FutureAndCallable2 {

	/**
	 * 使用ExecutorService的submit(Callable c)方法
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		Future<String> future=executorService.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "hello";
			}
		});
		System.out.println("--------");
		System.out.println(future.get());
	}

}

3 同時執行多次call方法,返回多個返回值,誰先執行完誰先返回

package com.lipeng;

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

public class FutureAndCallable2 {

	/**
	 * 使用ExecutorService的submit(Callable c)方法
	 * @param args
	 */
	public static void main(String[] args)throws Exception  {
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		CompletionService<Integer> cs=new ExecutorCompletionService(executorService);
		for(int i=0;i<10;i++)
		{
			final int j=i;
			cs.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					int time=new Random().nextInt(5000);
					Thread.sleep(time);
					
					return j;
				}
			});
		}
		
		System.out.println("---------------------------");
		for(int i=0;i<10;i++)
		{
			int a=cs.take().get();
			System.out.println(a);
		}
		executorService.shutdown();
	}

}


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