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;
}
}
}
多线程实现图片上传
最新推荐文章于 2025-06-10 09:17:24 发布
4685

被折叠的 条评论
为什么被折叠?



