package test;
import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DealFiles {
public static void main(String[] args) {
LocalDateTime startTime = LocalDateTime.now();
File newFile = new File("/data/test/test");
File[] files = newFile.listFiles();
ExecutorService service = Executors.newFixedThreadPool(files.lenght);
for (File file2 : files) {
System.out.println("文件名:"+file2.getName());
service.execute(new Runnable() {
@Override
public void run() {
System.out.println("文件名:"+file2.getName()+",开始处理时间:"+LocalDateTime.now());
try {
Thread.sleep(20*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("文件名:"+file2.getName()+",结束处理时间:"+LocalDateTime.now());
}
});
}
service.shutdown();
Boolean flag = true;
try {
flag = service.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
service.shutdown();
LocalDateTime endTime = LocalDateTime.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println("任务超时,共用时"+duration.toMillis());
}
if (flag) {
LocalDateTime endTime = LocalDateTime.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println("任务共用时"+duration.toMillis());
}
}
}
在run 方法里面直接加上处理慢的逻辑就可以了。最后 try 里面的可以不用这个,使用CountDownLatch 这个类基础也可以。cdl.await(10,TimeUnit.MINUTES);这样也可以。
这个线程池加在了之前在解析文件过程中,发过来的文件没有处理的快。