FutureTask的使用方法和使用实例

34 篇文章 0 订阅
5 篇文章 0 订阅
FutureTask是一种可以取消的异步的计算任务。它的计算是通过Callable实现的,它等价于可以携带结果的Runnable,并且有三个状态:等待、运行和完成。完成包括所有计算以任意的方式结束,包括正常结束、取消和异常。

Future有个get方法而获取结果只有在计算完成时获取,否则会一直阻塞直到任务转入完成状态,然后会返回结果或者抛出异常。

Executor框架利用FutureTask来完成异步任务,并[b]可以用来进行任何潜在的耗时的计算。一般FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果[/b]。

FutureTask有下面几个重要的方法:
1.get()
阻塞一直等待执行完成拿到结果

2.get(int timeout, TimeUnit timeUnit)
阻塞一直等待执行完成拿到结果,如果在超时时间内,没有拿到抛出异常

3.isCancelled()
是否被取消

4.isDone()
是否已经完成

5.cancel(boolean mayInterruptIfRunning)
试图取消正在执行的任务

package futuretask;

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

/**
*
*<p>Test</p>
*<p>Description:</P>
*<p>Company:</p>
*<p>Department:CAS</p>
*@Author: Tommy Zhou
*@Since: 1.0
*@Version:Date:2011-4-26
*
**/
public class FutureTaskSample {

static FutureTask<String> future = new FutureTask(new Callable<String>(){
public String call(){
return getPageContent();
}
});

public static void main(String[] args) throws InterruptedException, ExecutionException{
//Start a thread to let this thread to do the time exhausting thing
new Thread(future).start();
//Main thread can do own required thing first
doOwnThing();
//At the needed time, main thread can get the result
System.out.println(future.get());
}

public static String doOwnThing(){
return "Do Own Thing";
}
public static String getPageContent(){
return "testPageContent and provide that the operation is a time exhausted thing...";
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值