java CountDownLatch 多线程文件搜索
2016-03-08 00:18
363 查看
基于多线程搜索文件,并且将最终的结果进行打印。这里使用了CountDownLatch线程协作机制,主线程等待多个搜索线程完成,并对最终结果进行打印。另外使用了CopyOnWriteArrayList来保障多个线程保存操作结果的并发安全。具体例子如下:
package com.tuobana.concurrent.cyclibarrier; import java.io.File; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; /** * Created by lpn on 2016/3/7. */ public class SearchFile { public static void main(String argv[]) throws InterruptedException { List<String> results = new CopyOnWriteArrayList<String>(); String path = "e:/"; String searchName = "XXXStringUtil.java"; File file = new File(path); if (!file.exists() || !file.isDirectory()) { System.out.println("文件查找失败:" + path + "不是一个目录!"); } else { File files[] = file.listFiles(); if (files != null && files.length > 0) { CountDownLatch latch = new CountDownLatch(files.length); System.out.println("All thread started at " + new Date()); for (File f : files) { Thread t = new Thread(new SearchTask(f.getPath(), searchName, results, latch)); t.setName("Thread-" + f.getName()); t.start(); } latch.await(); System.out.println("All thread finished at " + new Date()); } } System.out.println(results.toString()); } } class SearchTask implements Runnable { private String path; private String fileName; private List<String> results; private CountDownLatch latch; public SearchTask(String path, String fileName, List<String> results, CountDownLatch latch) { this.path = path; this.fileName = fileName; this.results = results; this.latch = latch; } @Override public void run() { searchFile(this.path, this.fileName, this.results); latch.countDown(); } private void searchFile(String path, String fileName, List<String> results) { File file = new File(path); if (!file.exists() || !file.isDirectory()){ System.out.println("文件查找失败:" + path + "不是一个目录!"); } else { File files[] = file.listFiles(); if (files != null && files.length > 0) { for (File f : files) { if (f.isDirectory()) { searchFile(f.getAbsolutePath(), fileName, results); } else { if (f.getName().equals(fileName)) { results.add(f.getAbsolutePath()); } } } } } } }
相关文章推荐
- java单例模式就有6种,你知道哪几种?!
- 如何给maven项目增加新的jar包(从服务器上下载)---通过eclipse工具
- Java基础知识
- Leetcode:66. Plus One(JAVA)
- 一个经典例子让你彻彻底底理解java回调机制
- java 通过反射获取调用类方法及属性
- Spring学习笔记十一---通过注解配置bean
- Spring学习笔记十一---Bean之间的关系@Autowired
- Spring学习笔记十二---泛型依赖注入
- java线程同步的五种方法
- java正则表达式语法详解及其使用代码实例
- 深入理解Java 虚拟机(周志明)笔记(四)——Java对象创建过程
- 深入理解Java 虚拟机(周志明)笔记(三)——Java对象在内存中的存储与访问
- 深入分析 Java 中的中文编码问题
- Java设计模式
- Java线程池的设计与分析
- Java基础----反射Reflect---Field
- java thread join
- ajax进入springmvc后台返回中文乱码
- 5.5 Spring事务支持