countDownLatch配合线程池实现多文件上传

现在,我们想要上传多个文件,肯定是配合线程池最快,但是又想知道传递完之后文件的名字,以便返回给前端,
方法:
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之后再往下执行任务
CountDownLatch 是一个非常实用的多线程工具类,它可以让一个或多个线程等待其他线程完成执行后再继续执行。在多线程编程中,我们经常需要等待某些任务完成后才能进行下一步操作,这时就可以使用 CountDownLatch实现配合线程池使用 CountDownLatch 的基本思路如下: 1. 创建一个 CountDownLatch 对象,并设置计数器初始值为需要等待的线程数。 2. 创建一个线程池,然后提交需要等待执行的任务。 3. 在任务中调用 CountDownLatchcountDown() 方法来减少计数器的值。 4. 在主线程中调用 CountDownLatch 的 await() 方法来等待所有任务执行完毕。 下面是一个简单的示例代码: ```java import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); ExecutorService executorService = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { executorService.submit(new Worker(latch)); } latch.await(); System.out.println("All tasks are finished"); executorService.shutdown(); } static class Worker implements Runnable { private final CountDownLatch latch; public Worker(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { // 模拟执行任务 Thread.sleep((long) (Math.random() * 10000)); System.out.println(Thread.currentThread().getName() + " has finished the task"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } } } ``` 在上面的示例代码中,我们创建了一个 CountDownLatch 对象,计数器的初始值为 5。然后创建了一个线程池,提交了 5 个任务,并在任务中模拟了一定的执行时间。每个任务执行完毕后都会调用 CountDownLatchcountDown() 方法来减少计数器的值。最后,在主线程中调用 CountDownLatch 的 await() 方法来等待所有任务执行完毕。当所有任务都完成后,输出 "All tasks are finished"。 需要注意的是,在使用 CountDownLatch 时,计数器的初始值要与需要等待的线程数相等,否则可能会出现死锁的情况。另外,CountDownLatch 只能使用一次,计数器的值减少到 0 后就无法重置。如果需要重复使用,可以考虑使用 CyclicBarrier 或 Semaphore。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值