日期:2014-05-20 浏览次数:20703 次
import java.io.File; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class ListFileWithFutureTask { public static void main(String[] args) throws Exception { FutureTask<Integer> f=new FutureTask<Integer>(new Callable<Integer>(){ public Integer call(){ return search(new File("c:\\")); } }); Date begin=new Date(); f.run(); System.out.println(f.get()); Date end=new Date(); System.out.println(begin.getTime()-end.getTime()); } public static int search(File s){ //以下虽然产生了线程 但是效率还是一样低得可怕(线程等待...其实最多也就产生了一个 大错误....) final File[] ss=s.listFiles(); int count=0; if(ss!=null){ for(int i=0;i<ss.length;i++){ if(ss[i].isDirectory()){ final File sss=ss[i]; //若是目录 则建新线程开始计数 FutureTask<Integer> f=new FutureTask<Integer>(new Callable<Integer>(){ public Integer call(){ return search(sss); } }); f.run(); //这边会产生递归调用 但和单线程不同 这边的递归调用是多线的 try { count+=f.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }else{ count++; //不是文件就计数 } } } return count; } }
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.io.File; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class ListFileWithFutureTask2 { public static void main(String[] args) throws Exception { FutureTask<Integer> f=new FutureTask<Integer>(new Callable<Integer>(){ public Integer call(){ return search(new File("c:\\")); } }); Date begin=new Date(); f.run(); System.out.println(f.get()); Date end=new Date(); System.out.println(begin.getTime()-end.getTime()); } public static int search(File s){ final File[] ss=s.listFiles(); List<FutureTask<Integer>> fl=new ArrayList<FutureTask<Integer>>(); int count=0; if(ss!=null){ for(int i=0;i<ss.length;i++){ if(ss[i].isDirectory()){ final File sss=ss[i]; //若是目录 则建新线程开始计数 FutureTask<Integer> f=new FutureTask<Integer>(new Callable<Integer>(){ public Integer call(){ return search(sss); } }); f.run(); fl.add(f); }else{ count++; } } for(FutureTask<Integer> i:fl){ try { count=count+i.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return count; } }