现在,我们想要上传多个文件,肯定是配合线程池最快,但是又想知道传递完之后文件的名字,以便返回给前端,
方法:
countDownLatch能完美的配合线程池,其几个方法如下:
- 创建一个num数量的计数器
CountDownLatch countDownLatch=new CountDownLatch(num); - 减一操作
countDownLatch.countdown - 等到计数器变为0
countDownLatch.await();//注意是await!!
主线程会等待计数器变为0之后再往下执行任务
ArrayList<String>path=new ArrayList<>();
CountDownLatch countDownLatch=new CountDownLatch(file.length);
//2传文件
for(int i=0;i<file.length;i++){
int finalI = i;
executorService.submit(()->{
String p=System.currentTimeMillis()+file[finalI].getOriginalFilename();
try {
file[finalI].transferTo(new File("D:\\Aimg\\work\\"+p));
path.add(p);
} catch (IOException e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();//主线程会等待计数器变为0之后再往下执行任务