多线程实现图片上传

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ImageUploadExample {

    // 模拟图片路径列表,实际应用中替换为真实的待上传图片路径列表
    private static List<String> imagePaths = new ArrayList<>();

    static {
        // 这里简单模拟添加一些图片路径,实际中可以从文件系统等地方获取真实路径
        for (int i = 0; i < 100; i++) {
            imagePaths.add("image_path_" + i + ".jpg");
        }
    }

    public static void main(String[] args) {
        // 创建固定大小为200的线程池(原有的线程池)
        ExecutorService executorService = Executors.newFixedThreadPool(200);

        // 创建一个只允许同时运行50个任务的信号量,用于限制并发线程数量
        Semaphore semaphore = new Semaphore(50);

        // 用于存储所有的Future对象,以便后续获取结果
        List<Future<Boolean>> futures = new ArrayList<>();

        // 循环提交任务到线程池
        for (String imagePath : imagePaths) {
            ImageUploadCallable callable = new ImageUploadCallable(imagePath, semaphore);
            Future<Boolean> future = executorService.submit(callable);
            futures.add(future);
        }

        // 遍历获取每个任务的结果
        for (Future<Boolean> future : futures) {
            try {
                Boolean result = future.get();
                System.out.println("图片上传结果: " + result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池(虽然这里原需求说不断使用不关闭,但此处示例演示关闭情况,实际按需求来定)
        executorService.shutdown();
    }

    // 实现Callable接口的图片上传任务类
    static class ImageUploadCallable implements Callable<Boolean> {
        private String imagePath;
        private Semaphore semaphore;

        public ImageUploadCallable(String imagePath, Semaphore semaphore) {
            this.imagePath = imagePath;
            this.semaphore = semaphore;
        }

        @Override
        public Boolean call() {
            try {
                // 获取信号量许可,限制同时执行的线程数量为50
                semaphore.acquire();
                // 模拟图片上传操作,这里简单返回true表示上传成功,实际中替换为真实上传逻辑
                boolean uploadResult = uploadImage(imagePath);
                return uploadResult;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            } finally {
                // 释放信号量许可,确保线程资源释放
                semaphore.release();
            }
        }

        // 模拟图片上传方法,实际中要替换为真实的通过HTTP等方式上传图片到服务器的逻辑
        private boolean uploadImage(String imagePath) {
            System.out.println("正在上传图片: " + imagePath);
            // 这里简单模拟上传成功
            return true;
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值