public class scan {
private final Lock watchLock = new ReentrantLock();
@Resource(name = "pool")
private ThreadPoolExecutor pool=new ThreadPoolExecutor(3000,6000,5,TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardPolicy());;
private ArrayList<File> imgDirs;
private long allTasks = 0;
private long complatedTasks = 0;
private ReentrantReadWriteLock lockAll = new ReentrantReadWriteLock();
private ReentrantReadWriteLock lockComplate = new ReentrantReadWriteLock();
public static void main(String[] args) {
scan utilScan = new scan();
System.out.println(Arrays.toString(utilScan.scanLocalDir().toArray()));
}
public List<File> scanLocalDir() {
imgDirs = new ArrayList<File>();
File[] roots = File.listRoots();
try {
lockAll.writeLock().lock();
for (File root : roots) {
pool.submit(new FindDirRunable(root));
allTasks++;
}
} finally {
lockAll.writeLock().unlock();
}
long timestart = System.currentTimeMillis();
while (complatedTasks < 7000) {
//死循环监视是否结束,目前还有问题
System.out.print("allTasks = " + allTasks);
System.out.print(" complatedTasks = " + complatedTasks);
System.out.print(" getQueue() = " + pool.getQueue().size());
System.out.print(" getActiveCount() = " + pool.getActiveCount());
System.out.println(" getCompletedTaskCount() = " + pool.getCompletedTaskCount());
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ThreadPool.pool.shutdownNow();
System.out.println("end");
System.out.println(System.currentTimeMillis()-timestart);
System.out.print("allTasks = " + allTasks);
System.out.print(" complatedTasks = " + complatedTasks);
System.out.print(" getQueue() = " + pool.getQueue().size());
System.out.print(" getActiveCount() = " + pool.getActiveCount());
System.out.println(" getCompletedTaskCount() = " + pool.getCompletedTaskCount());
return imgDirs;
}
private class FindDirRunable implements Runnable {
private final File dir;
FindDirRunable(File dir) {
this.dir = dir;
}
@Override
public void run() {
// System.out.println(dir);
try {
File[] dirs = dir.listFiles();
boolean isImgDir = false;
if (dirs != null) {
for (File each : dirs) {//遍历文件夹下的东西
if (each.isFile()) {
if (!isImgDir) {//判断文件夹里有没有图片
String[] temp = each.getName().split("\\.");
// System.out.println(Arrays.toString(temp));
String type = temp[temp.length - 1];
if (Dict.imgTypes.contains(type.toLowerCase())) {
isImgDir = true;
imgDirs.add(dir);
}
}
} else if (each.isDirectory()) {//递归遍历文件夹
pool.submit(new FindDirRunable(each));
try {
lockAll.writeLock().lock();
allTasks++;
} finally {
lockAll.writeLock().unlock();
}
}
}
}
} finally {
//同步加 完成的任务数
try {
lockComplate.writeLock().lock();
complatedTasks++;
} finally {
lockComplate.writeLock().unlock();
}
// watchLock.notify();//每完成一个任务就唤醒主循环判断是不是所有任务都执行完了
}
}
}
;
}
评论区