FutureTask

来源:互联网 发布:王震对新疆的功过知乎 编辑:程序博客网 时间:2024/04/26 16:44
FutureTask是Future和Callable的结合体。传统的代码是这样写的

Future f = executor.submit(new Callable());

然后通过Future来取得计算结果。但是,若开启了多个任务,我们无从知晓哪个任务最先结束,因此,若要实现“当某任务结束时,立刻做一些事情,例如记录日志”这一功能,就需要写一些额外的代码。

FutureTask正是为此而存在,他有一个回调函数protected void done(),当任务结束时,该回调函数会被触发。因此,只需重载该函数,即可实现在线程刚结束时就做一些事情。

[java] view plaincopy
  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         ExecutorService executor = Executors.newCachedThreadPool();  
  4.         for(int i=0; i<5; i++) {  
  5.             Callable<String> c = new Task();  
  6.             MyFutureTask ft = new MyFutureTask(c);  
  7.             executor.submit(ft);  
  8.         }  
  9.         executor.shutdown();  
  10.     }  
  11.           
  12. }  
  13.   
  14. class MyFutureTask extends FutureTask<String> {  
  15.   
  16.     public MyFutureTask(Callable<String> callable) {  
  17.         super(callable);  
  18.     }  
  19.   
  20.     @Override  
  21.     protected void done() {  
  22.         try {  
  23.             System.out.println(get() + " 线程执行完毕!~");  
  24.         } catch (InterruptedException | ExecutionException e) {  
  25.             // TODO Auto-generated catch block  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.       
  30.       
  31. }  
  32.   
  33. class Task implements Callable<String> {  
  34.   
  35.     @Override  
  36.     public String call() throws Exception {  
  37.         Random rand = new Random();  
  38.         TimeUnit.SECONDS.sleep(rand.nextInt(12));  
  39.         return Thread.currentThread().getName();  
  40.     }  
  41. }  
0 0
原创粉丝点击