FutureTask的使用方法和使用实例

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

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

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

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...";
    }
}

猜你喜欢

转载自tomyz0223.iteye.com/blog/1019924