java.util.concurrent.Future浅析

在学习多线程的时候,看到了Future这个接口,学习了一下,记录下来。

        Future接口是一个泛型接口,严格来说是Future<V>。Future一般用于比较耗时的操作,但不处理又不行,那么就可以把这个任务交给Future来处理,我们可以做其他的事情,等Future处理好这个耗时的任务后,会返回给我们处理后信息。具体的实现类为java.util.concurrent.FutureTask<V>。

        jdk中的描述是:

        A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by thecancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use aFuture for the sake of cancellability but not provide a usable result, you can declare types of the formFuture<?> and return null as a result of the underlying task.

       翻译出来就是:

   Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用 get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明Future<?> 形式类型、并返回 null 作为底层任务的结果。

       网上的例子比较好,我就摘抄过来了,请作者见谅:

 

package com.bao.study;

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

public class TestFutureTask {
	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		final ExecutorService exec = Executors.newFixedThreadPool(5);
		Callable<String> call = new Callable<String>() {
			public String call() throws Exception {
				Thread.sleep(1000 * 3);//休眠指定的时间,此处表示该操作比较耗时
				return "Other less important but longtime things.";
			}
		};
		Future<String> task = exec.submit(call);
		//重要的事情
		Thread.sleep(1000 * 3);
		System.out.println("Let's do important things.");
		//不重要的事情
		String obj = task.get();
		System.out.println(obj);
		//关闭线程池
		exec.shutdown();
	}
}

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值