例:递归遍历文件夹,多线程处理文件夹内的文件。
有下面两种实现,都是递归遍历文件夹查找其中的文件,区别是第一种是遍历到文件即交给线程进行处理,第二种将遍历到的文件存入队列中,多线程到队列中取任务并行处理。
(一)
package com.nvshen.job.scheduling;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ClassA{
private static final ExecutorService es = Executors.newFixedThreadPool(10);
private static void searchFile(final File f) throws InterruptedException {
if (f != null) {
if (f.isDirectory()) {
File[] fir = f.listFiles();
if (fir != null) {
for (int i = 0; i < fir.length; i++) {
searchFile(fir[i]);
}
}
} else {
es.submit(new Runnable() {
public void run() {
try {
//对文件f进行处理
} catch (Exception e) {
}
}
});
}
} else {
System.out.println("该路径没有文件");
}
}
public static void main(String[] args){
File file = new File("E://picture/跃层/");
try {
searchFile(file);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
(二)
public class ClassB {
private static final ExecutorService es = Executors.newFixedThreadPool(10);
private static void searchFile(final File f) throws InterruptedException {
if (f != null) {
if (f.isDirectory()) {
File[] fir = f.listFiles();
if (fir != null) {
for (int i = 0; i < fir.length; i++) {
searchFile(fir[i]);
}
}
} else {
es.submit(new Runnable() {
public void run() {
try {
//对文件f进行处理
} catch (Exception e) {
}
}
});
}
} else {
System.out.println("该路径没有文件");
}
}
public static void main(String[] args){
File file = new File("E://picture/跃层/");
try {
searchFile(file);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}