您的位置:首页 > 编程语言 > Java开发

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());
}
}
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: