同步工具类之FutureTask

2017-01-10  本文已影响104人  evil_ice
一,FutureTask概述
  • FutureTask也可以用作闭锁.FutureTask实现了Future语义,表示一种抽象的可生成结果的计算.FutureTask表示的计算是通过Callable来实现的,相当于一种可生成结果的Runnable,并且可以处于以下3种状态:等待运行,正在运行和运行完成.
二,Callable, Future, FutureTask的关系
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);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask.png
三,一个小示例
public class Test {
    public static void main(String[] args){
        FutureAndCallableDemo demo = new FutureAndCallableDemo();
        List<Callable<String>> tasks = new ArrayList<Callable<String>>();
        for(int i=0; i<5; i++){
            tasks.add(new Task());
        }
        
        List<String> results = demo.executeTask(tasks);
        for(String result : results){
            System.out.println(result);
        }
    }
}

class Task implements Callable<String>{
    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName()+"  "+System.currentTimeMillis();
    }   
}

class FutureAndCallableDemo{
    ExecutorService executor = Executors.newCachedThreadPool();
    
    public List<String> executeTask(List<Callable<String>> tasks){
        List<String> results = new ArrayList<String>();
        for(Callable<String> task : tasks){
            FutureTask<String> result = new FutureTask<String>(task);
            Thread thread = new Thread(result);
            thread.start();
            try {
                results.add(result.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        return results;
    }

}

参考:
<<java编发编程实战>>

上一篇下一篇

猜你喜欢

热点阅读