本文主要是介绍【中国大学MOOC】java程序设计-week8-多线程爬虫,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.题目
下面的程序可以下载多个网页文件(download方法已写好),请将它改成多线程进行下载(评分占7分),如果可能, 显示计算全部下载完成程序所用的时间(提示:new Date().getTime()可以得到当前时间的毫秒数,评分占3分)。另外,请注意一下,
系统中http:传到平台后,它自动改成了https:,所以请改回http:。 另外,有一些链接访问不了,所以要注意加try…catch。
import java.net.URL;
import java.io.*;class Downloader
{public static void main(String[] args)throws Exception{final URL[] urls = {new URL("https://www.pku.edu.cn"),new URL("https://www.baidu.com"),new URL("https://www.sina.com.cn"),new URL("https://www.dstang.com")};final String[] files = {"pku.htm", "baidu.htm","sina.htm", "study.htm",};for(int idx=0; idx<urls.length; idx++){try{System.out.println( urls[idx] );download( urls[idx], files[idx]);}catch(Exception ex){ex.printStackTrace();}}}static void download( URL url, String file)throws IOException{try(InputStream input = url.openStream();OutputStream output = new FileOutputStream(file)){byte[] data = new byte[1024];int length;while((length=input.read(data))!=-1){output.write(data,0,length);}}}
}
2.题解
import java.net.URL;
import java.io.*;
import java.util.Date;public class homework8
{public static void main(String[] args)throws Exception{final URL[] urls = {new URL("https://www.pku.edu.cn"),new URL("https://www.baidu.com"),new URL("https://www.sina.com.cn"),new URL("https://www.dstang.com")};final String[] files = {"pku.htm","baidu.htm","sina.htm","study.htm",};// 新建线程Thread t0 = new MyThread(urls[0], files[0]);Thread t1 = new MyThread(urls[1], files[1]);Thread t2 = new MyThread(urls[2], files[2]);Thread t3 = new MyThread(urls[3], files[3]);// 运行线程t0.start();t1.start();t2.start();t3.start();}
}
/*
新建线程类,继承Thread*/
class MyThread extends Thread {URL url;String file;public MyThread(URL url, String file){super();this.url = url;this.file = file;}public void run() {long time1 = new Date().getTime(); // 计算开始时的时间time1java.io.InputStream input = null;java.io.OutputStream output = null;try{try{input = url.openStream();output = new FileOutputStream(file);byte[] data = new byte[1024];int length;while((length=input.read(data))!=-1){output.write(data,0,length);}}catch(IOException e1){e1.printStackTrace();}}catch(Exception ex) {ex.printStackTrace();}finally{long time2 = new Date().getTime(); // 计算结束后的时间time2System.out.println("本次下载耗时" + (time2-time1) + "ms"); // 计算下载耗时time2-time1}}
}
这篇关于【中国大学MOOC】java程序设计-week8-多线程爬虫的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!