基於多線程搜索文件,並且將最終的結果進行打印。這裏使用了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());
}
}
}
}
}
}
}