本答案对应课程为:点我自动跳转查看
本课程起止时间为:2020-02-17到2020-07-04
本篇答案更新状态:已完结
【作业】第8讲 多线程 Week8 互评作业
1、 问题:下面的程序可以下载多个网页文件(download方法已写好),请将它改成多线程进行下载(评分占7分),如果可能, 显示计算全部下载完成程序所用的时间(提示:new Date().getTime()可以得到当前时间的毫秒数,评分占3分)。import java.net.URL;
import java.io.*;
class Downloader
{
public static void main(String[] args)
throws Exception
{
final URL[] urls = {
new URL(“http://www.pku.edu.cn”),
new URL(“http://www.baidu.com”),
new URL(“http://www.sina.com.cn”),
new URL(“http://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);
}
}
}
}
评分规则: 【 使用了多线程,且程序能正常运行
正确显示了所用时间
总体较好,或使用了Lambda表达式等特殊手段
】 点我阅读全文