当前位置: 首页 > news >正文

wordpress+整容模板重庆网站优化排名推广

wordpress+整容模板,重庆网站优化排名推广,wordpress情侣模板,哈尔滨seo优化排名JVM是支持多线程程序的,当程序需要同时执行两个或多个任务,实现一些需要等待的任务时,如用户输入、文件读写、网络操作、搜索等多线程程序比单线程程序更具优势,可充分利用CPU资源,完成时间更短,提高应用程…

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

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

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

在这里插入图片描述

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

<!-- 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>

完整代码:

/*** 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);}@Autowiredprivate 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上。
http://www.zhongyajixie.com/news/26261.html

相关文章:

  • 免费的带货视频素材网站电商网站建设方案
  • 在哪里做网站效果好如何免费创建自己的平台
  • 安徽建设网seo排名优化推广报价
  • 丽江市住房和城乡建设局网站怎样推广
  • 自己做简单网站晋城网站seo
  • 如何做博客网站超级外链吧外链代发
  • 网站关键词排名没有了登封网站关键词优化软件
  • 企业网站建设流程第一步是什么建站
  • 什么软件做电影短视频网站深圳专业seo
  • 上海到北京飞机几个小时广州网站营销优化qq
  • 深圳网站建设优化服务seo关键词排名优化专业公司
  • 做网站泊头百度网页
  • a片做视频网站论坛seo教程
  • 论坛网站建设费用有哪些搜索引擎
  • 新网站做百度百科公司网站怎么弄
  • 肯德基网站是哪家公司做的百度店铺怎么入驻
  • 贵州住房和城乡建设厅旧网站赚钱平台
  • 帝国网站后台操作培训ppt2345网址中国最好
  • 网站做收录软文写作
  • 合肥建筑网站百度推广优化师是什么
  • 做电子简历的网站能翻到国外的浏览器
  • 手机开网店0元加盟店广州seo报价
  • 无锡专业做网站的公司模板网站建站公司
  • 网站开发技术与vb泰州百度seo
  • 安卓app开发如何获取网站的seo
  • 叫外包公司做网站不肯给源代码的seo百度关键词排名
  • 跨境电商网站如何做推广济南网站建设哪家好
  • 258网站建设培训课程安排
  • 金融网站建设成功案例营销咨询公司排名
  • 做网站多少钱_西宁君博优选seo推广费用