好贷网好贷款

callable 和 futrue 线程并发

发布时间:2016-12-4 20:28:54 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"callable 和 futrue 线程并发",主要涉及到callable 和 futrue 线程并发方面的内容,对于callable 和 futrue 线程并发感兴趣的同学可以参考一下。

package org.chapter.thread; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class FutrueTest { public static void main(String[] args) throws InterruptedException, ExecutionException { Scanner in=new Scanner(System.in); System.out.print("请输入文件目录:"); String directory=in.nextLine(); System.out.print("请输入关键字:"); 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(); System.out.println("matching files:"+task.get()); } } class MatchCounter implements Callable<Integer> { private File directory; private String keyword; private int count; public MatchCounter(File directory, String keyword) { this.directory = directory; this.keyword = keyword; } @Override public Integer call() throws Exception { count = 0; 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 (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return count; } 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(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }

上一篇:有限状态机的嵌入式Linux按键驱动设计(转载)
下一篇:hibernate 数据保存操作的原理

相关文章

相关评论