求java多线程遍历目录的完整代码,能运行的那种

求java多线程遍历目录的完整代码,能运行的那种,第1张

目录结构为树型结构,用多线程不大好做,线程最多在前几层进行分割,比如每个目录下有两个目录,共5层,那么root目录下就能启用2个线程分别进行遍历,所以第二层就启动了2个线程进行遍历,加上主线程共三个线程,虽然这样做是可以做,但是要更具实际情况进行线程的规划,否则容易线程过多导致cpu超负荷,或者假死,再提一点,遍历目录不建议用递归来写,因为目录较多容易栈溢出。

随手写了个,会有点bug就是关闭线程池的时候,还有就是有可能目录太多进入拒绝策略,这个东西 可以考虑使用令牌桶算法,或者计数器算法来做。这里提供个简单的例子。

public class TraverseUtil {

public static BlockingQueue blockingQueue = new LinkedBlockingQueue(100)

public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100,100,10, TimeUnit.SECONDS,blockingQueue)

public static void traverseFolder2(String path) {

File file = new File(path)

if (file.exists()) {

File[] files = file.listFiles()

if (null == files || files.length == 0) {

System.out.println("文件夹是空的!")

return

} else {

for (File file2 : files) {

if (file2.isDirectory()) {

System.out.println("文件夹:" + file2.getAbsolutePath())

threadPoolExecutor.execute(new Runnable() {

@Override

public void run() {

traverseFolder2(file2.getAbsolutePath())

}

})

} else {

System.out.println("文件:" + file2.getAbsolutePath())

}

}

}

} else {

System.out.println("文件不存在!")

}

}

public static void main(String[] args) throws InterruptedException {

traverseFolder2("C:\\Users\\a8932\\Desktop\\md")

}

}

1、根据API中的文件和目录 *** 作函数构成一个具有递归功能的目录遍历和文件查找

2、可以根据MFC中对线程的封装格式,将上述 *** 作放入线程函数中

3、更多交流参考我空间文章。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11992259.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存