本文主要是介绍多线程下载网络资源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
示例:模拟通过5个线程下载10个网络图片
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;public class MultiThreadDownloader {private static final int THREAD_POOL_SIZE = 5;//线程池大小private List<String> networkResources = new ArrayList<>();//模拟10个网络资源private static final String downloadPath = "E:/Tmp";//下载目录public void download() throws IOException, ExecutionException, InterruptedException {//记录开始时间LocalDateTime currentTime = LocalDateTime.now();DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String startTime = currentTime.format(formatter);System.out.println("下载开始时间:" + startTime);List<String> executeResult = new ArrayList<>();//创建线程池,多线程下载ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);for(String resource:networkResources) {Future<String> future = executorService.submit(new Callable<String>() {@Overridepublic String call() throws Exception {String fileNameSuffix = resource.substring(resource.lastIndexOf("/") + 1);String fileName = downloadPath + File.separator + fileNameSuffix;//文件名和下载地址保持一致File file = new File(fileName);OutputStream outputStream = null;URL url = null;URLConnection urlConnection = null;InputStream inputStream = null;try {outputStream = new FileOutputStream(file);url = new URL(resource);urlConnection = url.openConnection();inputStream = urlConnection.getInputStream();byte[] bytes = new byte[1024];int len = 0;while ((len = inputStream.read()) != -1) {outputStream.write(bytes,0,len);}} catch (FileNotFoundException | MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}executeResult.add("success");return "success";}});//future.get();//等待线程执行结果}executorService.shutdown();System.out.println(executeResult);//记录结束时间currentTime = LocalDateTime.now();String endTime = currentTime.format(formatter);System.out.println("下载结束时间:" + endTime);}public void initDownLoadTask() {networkResources.add("https://pics5.baidu.com/feed/7aec54e736d12f2e20ef4daf3258436c87356844.jpeg");networkResources.add("https://pics7.baidu.com/feed/0ff41bd5ad6eddc42349d0dd474120f353663396.jpeg");networkResources.add("https://pics5.baidu.com/feed/d53f8794a4c27d1e50c0a932080c3b60dfc4384d.jpeg");networkResources.add("https://pics5.baidu.com/feed/95eef01f3a292df5559aa4dab3c0ca6e36a873a7.jpeg");networkResources.add("https://pic.rmb.bdstatic.com/bjh/news/21bf5f01d0fc4d31e1c49167f92ee023.jpeg");networkResources.add("https://pic.rmb.bdstatic.com/bjh/news/4a11f9b43570c2ef89ea4f0c61c8fb19.jpeg");networkResources.add("https://pics5.baidu.com/feed/e4dde71190ef76c675521117d99b6bf4ae5167a2.png");networkResources.add("https://pics5.baidu.com/feed/342ac65c10385343dae1dbe2d19e2670cb808866.jpeg");networkResources.add("https://pics1.baidu.com/feed/64380cd7912397dd1b012247d50d24b9d1a28793.jpeg");networkResources.add("https://pics7.baidu.com/feed/95eef01f3a292df531693cbf37beca6e35a87314.jpeg");}public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {MultiThreadDownloader downloader = new MultiThreadDownloader();downloader.initDownLoadTask();downloader.download();}
}
这篇关于多线程下载网络资源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!