Callable&&Future的基本使用

ExecutorService的submit

ExecutorService的submit方法可以接收一个Callable<T>对象,并且返回一个Future<V> 。

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
public interface Future<V> {
	//取消执行的任务
    boolean cancel(boolean mayInterruptIfRunning);
    //如果任务在未完成之前取消,则返回true
    boolean isCancelled();
    //任务完成,返回true
    boolean isDone();
    //	等待返回的结果
    V get() throws InterruptedException, ExecutionException;
    //按照指定的时间去获取执行的结果,
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
class MyCallable1 implements Callable<String> {
	public String call() throws Exception {
		return " method call is running";
	};
}
@Test
public void test01() throws Exception {
	// 1、创建线程池
	ExecutorService threadPool = Executors.newSingleThreadExecutor();
	// 2、提交任务、获取返回值
	Future<String> future = threadPool.submit(new MyCallable1());
	//3、输出返回值
	System.out.println(future.get());
	threadPool.shutdown();
}

CompletionService

可以提交一组Callable,并使用take方法返回已完成一个Callable任务对应的Future对象。
class MyCallable2 implements Callable<Integer>  {
	private int seq ;
	public MyCallable2(int seq){
		this.seq = seq;
	}
	@Override
	public Integer call() throws Exception {
		Thread.sleep(new Random().nextInt(5000));
		return seq;
	}
}
@Test
public void test02() throws Exception {
	ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
	CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
	for (int i = 1; i <= 10; i++) {
		completionService.submit(new MyCallable2(i));
	}
	for (int i = 0; i < 12; i++) {
		System.out.println("start >> "+i);
		System.out.println(completionService.take().get());
		System.out.println("end >> "+i);
		//如果没有拿到结果,会阻塞在那里。
	}
	threadPool2.shutdown();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值