Runnable封装一个异步运行的任务;你可以把它想像成一个没有任何参数和返回值的异步方法。Callable和Runnable相似,但它有返回值。Callable接口是一个参数化的类型,只有一个方法call。

public interface Callable<V>
{V call() throws Exception;
}

类型参数是返回值的类型。例如,Callable<Integer>代表一个最终返回Integer对象的异步计算。
   Future保存异步计算的结果。当你使用Future对象时,你就可以启动一个计算,把计算结果给某线程,然后就去干你自己的事。Future对象的所有者在结果计算好之后就可以得到它。
   Future接口具有下面的方法:

public interface Future<V>
{ V get() throws ...;V get(long timeout, Timeout unit) throws ...;void cancel(boolean mayInterrupt);boolean isCancelled();boolean isDone();
}

第一个get方法的调用将被阻塞,直至计算完成。第二个get方法的调用如果在计算完成之前超时,那么将抛出TimeoutException异常。如果运行计算的线程被中断,这两个方法都将抛出InterruptedException异常。如果计算已经完成,那么get方法将立即返回。
   如果计算还在进行中,isDone方法将返回false,如果计算已经完成则返回true。
   你可以使用cancel方法取消计算。如果计算还没开始,它会被取消并永远不会开始。如果计算正在进行,那么,如果mayInterrupt参数值为true,它就会被中断。
   FutureTask包装器是一种很方便的将Callable转换成Future和Runnable的机制,它同时实现了两者的接口。例如,

Callable<Integer> myComputation = ...;
FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
Thread t = new Thread(task);//it's a Runnable
t.start();
...
Integer result = task.get();//it's a Future

下面的程序中使用了这些概念。这个程序与前面那个寻找包含指定关键字文件的例子相似。但是,现在我们仅仅是计算匹配的文件数量。因此,我们有了一个长时间运行的任务,它产生一个整数值,一个Callable<Integer>的例子。

class MatchCounter implements Callable<Integer>
{public MatchCounter(File directory,String keyword){...}public Integer call() {...}//return the number of matching files
}

然后我们利用MatchCounter创建一个FutureTask对象,并使用它来启动一个线程。

FutureTask<Integer> task = new FutureTask<Integer>(counter);
Thread t = new Thread(task);
t.start();

最后,我们打印出结果:

System.out.println(task.get()+" matching files.");

当然,对get的调用会发生阻塞知道有可获得的结果为止。
在call方法内部,我们使用相同的递归机制。对于每一个子目录,我们产生一个MatchCounter并为它启动一个线程。此外,我们还把FutureTask对象隐藏在ArrayList<Integer>中。最后,我们把所有结果加起来:

for(Future<Integer> result: results)count += result.get();

每次对get的调用都会发生阻塞直到有结果可获得为止。当然,线程是并行运行的,因此很有可能在大致相同的时刻,所有的结果都可获得。

import java.io.*;
import java.util.*;
import java.util.concurrent.*;public class FutureTest
{public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");String directory = in.nextLine();System.out.print("Enter keyword (e.g. volatile): ");String keyword = in.nextLine();MatchCounter counter = new MatchCounter(new File(directory), keyword);FutureTask<Integer> task = new FutureTask<Integer>(counter);Thread t = new Thread(task);t.start();try{System.out.println(task.get() + " matching files.");}catch (ExecutionException e){e.printStackTrace();}catch (InterruptedException e){}}
}/*** This task counts the files in a directory and its subdirectories that contain a given keyword.*/
class MatchCounter implements Callable<Integer>
{/*** Constructs a MatchCounter.* @param directory the directory in which to start the search* @param keyword the keyword to look for*/public MatchCounter(File directory, String keyword){this.directory = directory;this.keyword = keyword;}public Integer call(){count = 0;try{File[] files = directory.listFiles();ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();for (File file : files)if (file.isDirectory()){MatchCounter counter = new MatchCounter(file, keyword);FutureTask<Integer> task = new FutureTask<Integer>(counter);results.add(task);Thread t = new Thread(task);t.start();}else{if (search(file)) count++;}for (Future<Integer> result : results)try{count += result.get();}catch (ExecutionException e){e.printStackTrace();}}catch (InterruptedException e){}return count;}/*** Searches a file for a given keyword.* @param file the file to search* @return true if the keyword is contained in the file*/public boolean search(File file){try{Scanner in = new Scanner(new FileInputStream(file));boolean found = false;while (!found && in.hasNextLine()){String line = in.nextLine();if (line.contains(keyword)) found = true;}in.close();return found;}catch (IOException e){return false;}}private File directory;private String keyword;private int count;
}

转载于:https://www.cnblogs.com/XL-Liang/archive/2012/06/13/2548032.html

基于Callable和Future的匹配文件数量计算实例相关推荐

  1. 基于灰度信息(块匹配)的图像拼接系统——MATLAB实现,带GUI界面!!!

    基于灰度信息的图像拼接简介 基于灰度相关的匹配是在待定点为中心的窗口内,以图像的灰度分布为匹配的内容,故称之为灰度匹配.又因为匹配是以划分的图像块为单位进行的,所以又称为块匹配(Block Match ...

  2. linux 统计日志数量总,shell统计日志中时间段内匹配的数量的方法

    shell统计日志中时间段内匹配的数量的方法,有需要的朋友可以参考下. 假设日志文件mtasvr.log格式如下: T:24583088(04:02:06)[root:Info] 6KqowLDLAg ...

  3. 解析 Callable Runnable Future 使用和原理

    2019独角兽企业重金招聘Python工程师标准>>> 概念 Callable类的定义 @FunctionalInterface public interface Callable& ...

  4. Java多线程-Callable和Future

    Callable和Future出现的原因 创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需 ...

  5. TF之TFOD-API:基于tensorflow框架利用TFOD-API脚本文件将YoloV3训练好的.ckpt模型文件转换为推理时采用的.pb文件

    TF之TFOD-API:基于tensorflow框架利用TFOD-API脚本文件将YoloV3训练好的.ckpt模型文件转换为推理时采用的frozen_inference_graph.pb文件 目录 ...

  6. terminated 线程_Java【多线程系列】JUC线程池—2. 原理(二)、Callable和Future

    在"Java多线程系列--"基础篇"01之 基本概念"中,我们介绍过,线程有5种状态:新建状态,就绪状态,运行状态,阻塞状态,死亡状态.线程池也有5种状态:然而 ...

  7. Java多线程系列--“JUC线程池”06之 Callable和Future

    转载自  Java多线程系列--"JUC线程池"06之 Callable和Future Callable 和 Future 简介 Callable 和 Future 是比较有趣的一 ...

  8. 基于C++与VS2012的HDF5文件处理(一)

    基于C++与VS2012的HDF5文件处理(一) 前言 随着研究的不断深入,处理的数据量越来越大,普通的数据格式读取速度慢,传输效率低等问题暴露无遗,计算时不得不使用一些复杂的数据格式.比起level ...

  9. mysql的请求分发,基于 gorilla/mux 实现路由匹配和请求分发:服务单页面应用

    基于 gorilla/mux 实现路由匹配和请求分发:服务单页面应用 由 学院君 创建于1年前, 最后更新于 1年前 版本号 #1 1279 views 0 likes 0 collects 随着前后 ...

最新文章

  1. Flutter编译时生成代码之 code_builder
  2. SIGGRAPH最佳博士论文奖又落华人手中,胡渊鸣的这位师兄不一般
  3. ios怎么安装python3.7_Python3、PyCharm的安装及使用方法(Mac版)
  4. ci发什么音标_48个国际音标发音舌位图
  5. 我的第一程序语言python
  6. node.js提供的服务器live-server的使用
  7. mysql安装服务和安装中常见问题install/Remove of the Service Denied与net start mysql服务启动失败解决方法
  8. sql查询优化7种方法
  9. mac 显示及隐藏文件的方法
  10. python 按行读取_python按行读取
  11. Linux系统升级及内核版本升级
  12. 用Python学《微积分B》(单调性与极值,凸性与拐点)
  13. 第二章 第六课 Scratch作品:摇摇晃晃的虫子(随机数和碰到边缘就反弹)
  14. 嵌入式Web项目(一)——Web服务器的引入
  15. 【2018年总】——感谢遇见,感谢拥有,感谢失去
  16. Python爬取猫眼「碟中谍」全部评论~
  17. windows8从安装到优化详细全过程——超详细图文教程
  18. 汽车后市场助理—行驶证识别
  19. HTTP contentType
  20. 国家开放大学2021春1133文献检索题目

热门文章

  1. html页面锁屏,JavaScript网页锁屏效果源码实例
  2. 我最讨厌哪种数据分析师?这四点全中就可以辞职走人了
  3. 主流的数据可视化工具介绍
  4. BlazeDS4 添加MSSQL/MySQL数据源
  5. Flex App的Size和Link报告
  6. python3.8.2安装ipython_CentOS系统 python3+python2 Ipython安装
  7. 数据结构 5-0 树与二叉树总结
  8. 数据结构实验 9.求逆序对数
  9. 数据结构实验 4.括号画家
  10. CSDN上下标输入方法