Java多线程下载文件

JVM是支持多线程程序的,当程序需要同时执行两个或多个任务,实现一些需要等待的任务时,如用户输入、文件读写、网络操作、搜索等多线程程序比单线程程序更具优势,可充分利用CPU资源,完成时间更短,提高应用程序的响应,增强用户体验。因此学会改善程序结构,将即长又复杂的进程分为多个线程,独立去运行,对于开发者来说至关重要。

以下载多个文件为例,如何使用多线程机制,高效率的完成下载任务?且听我我慢慢道来。

提出需求:编写一个API,打包下载GitHub的所有用户头像(以zip形式返回所有用户头像)。

文件压缩我们统一使用apache的commons-compress相关类进行压缩,因此需要引入相关的依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.24.0</version>
</dependency>

完整代码:

java 复制代码
/**
 * TODO
 *
 * @Description
 * @Author laizhenghua
 * @Date 2023/8/31 09:22
 **/
@RestController
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Autowired
    private ServletContext servletContext;

    @GetMapping("/test")
    public void test() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        RestTemplate restTemplate = new RestTemplate();
        String usersUrl = "https://api.github.com/users";

        // 查询github用户信息
        JSONArray userList = restTemplate.getForObject(usersUrl, JSONArray.class);
        if (CollectionUtils.isEmpty(userList)) {
            fallback("下载失败,失败原因: 查询为空", response);
            return;
        }
        // 下载路径准备
        String rootPath = servletContext.getRealPath("/") + "avatars";
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdir();
        }

        // 初始化线程池(JDK 5.0新增的线程池API更多知识可自行学习)
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        userList.forEach(item -> {
            JSONObject user = new JSONObject((Map)item);
            String login = user.getString("login"); // github登录名
            String downloadUrl = user.getString("avatar_url"); // 头像下载地址
            String filePath = rootPath + File.separator + login + ".png";
            // 执行下载任务(下载至本地)
            // ****** 一个线程处理一个用户(主线程只负责提交任务尽可能把耗时逻辑都放到多线程任务里如下载、IO操作等) ******
            executorService.execute(() -> {
                try {
                    File file = new File(filePath);
                    boolean newFile = file.createNewFile();
                    if (!newFile) {
                        return;
                    }
                    String name = Thread.currentThread().getName();
                    String log = String.format("%s download start download path: %s", name, filePath);
                    System.out.println(log);
                    // 调用下载接口获取输入流程
                    ResponseEntity<Resource> responseEntity = restTemplate.getForEntity(downloadUrl, Resource.class);

                    // 将得到的输入流写入文件
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        inputStream = Objects.requireNonNull(responseEntity.getBody()).getInputStream();
                        outputStream = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.close(inputStream);
                        IOUtils.close(outputStream);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });

        // 关闭线程池
        executorService.shutdown();

        // 使用org.apache.commons类压缩下载好的头像
        ZipArchiveOutputStream zipAos = null;
        try {
            // 等待线程池中所有任务执行完成(指定时间内没有执行完则返回false)
            boolean allTaskCompleted = executorService.awaitTermination(30, TimeUnit.MINUTES);
            if (!allTaskCompleted) {
                fallback("下载失败", response);
            }
            // 设置下载信息
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("github_avatar.zip", "utf-8") + "\"");
            response.setContentType("application/zip");

            zipAos = new ZipArchiveOutputStream(response.getOutputStream());
            zipAos.setEncoding("UTF-8");
            zipAos.setUseZip64(Zip64Mode.AsNeeded);

            File[] files = root.listFiles(); // 获取所有下载好的头像
            assert files != null;
            for (File file : files) {
                // 将头像压缩至 github_avatar.zip 文件
                ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName());
                entry.setLastModifiedTime(FileTime.fromMillis(file.lastModified()));
                zipAos.putArchiveEntry(entry);
                try (InputStream inputStream = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        zipAos.write(buffer, 0, len);
                    }
                    file.delete();
                }
            }
            zipAos.closeArchiveEntry();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(zipAos);
        }
    }

    private void fallback(String message, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = null;
        try {
            R error = R.error(500, message);
            JSONObject json = new JSONObject(error);
            writer = response.getWriter();
            writer.append(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}

对于打包下载,我们可以用单线程,也可以用多线程,处理这种任务多线程的优势就体现出来了,可自行对比下单线程和多线程程序响应速度。

使用多线程需要注意的是:

  1. Executors.newFixedThreadPool()是创建一个可重用固定线程数量的线程池。
  2. 主线程只负责分配任务,把耗时的逻辑尽可能的写到多线程任务上独立执行。
  3. 使用完线程池必须要关闭,先调用 shutdown() 方法关闭线程池,然后调用 awaitTermination(long timeout, TimeUnit unit) 方法等待线程池中的所有任务执行完成,只有线程池中的所有任务都执行完了,才能把响应信息写到response上。
相关推荐
技术无疆10 分钟前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
2401_8582861113 分钟前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py14 分钟前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy14 分钟前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
C-SDN花园GGbond2 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处3 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ3 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6253 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
拾光师4 小时前
spring获取当前request
java·后端·spring
aPurpleBerry4 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j