多线程下载图片

 1 import java.io.File;
 2 import java.io.IOException;
 3 import java.net.MalformedURLException;
 4 import java.net.URL;
 5 
 6 import org.apache.commons.io.FileUtils;
 7 /*
 8  * 下载类
 9  */
10 public class WebDownload {
11     public void download(String url,String name){
12         try {
13             FileUtils.copyURLToFile(new URL(url), new File(name));
14         } catch (MalformedURLException e) {
15             System.out.println("不合法的URL");
16         } catch (IOException e) {
17             System.out.println("下载失败");
18         }
19         
20     }
21 
22 }
 1 /*
 2  * 多线程实现方式一
 3  */
 4 public class DownLoader extends Thread{
 5     private String url;
 6     private String name;
 7     public DownLoader(String url, String name) {
 8         super();
 9         this.url = url;
10         this.name = name;
11     }
12     @Override
13     public void run() {
14         WebDownload wdl=new WebDownload();
15         wdl.download(url, name);
16         System.out.println(this.getName());
17     }
18     public static void main(String[] args) {
19         DownLoader dl1=new DownLoader("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1237924924,3470614764&fm=26&gp=0.jpg","tupian/haitun.jpg");
20         DownLoader dl2=new DownLoader("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1317686978,2345730812&fm=26&gp=0.jpg","tupian/laoshu.jpg");
21         DownLoader dl3=new DownLoader("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2531381064,3648016782&fm=26&gp=0.jpg","tupian/tiger.jpg");
22         dl1.start();
23         dl2.start();
24         dl3.start();
25     }
26 
27 }
 1 /*
 2  * 多线程实现方式二
 3  */
 4 public class DownLoader2 implements Runnable{
 5     private String url;
 6     private String name;
 7     
 8 
 9     public DownLoader2(String url, String name) {
10         super();
11         this.url = url;
12         this.name = name;
13     }
14 
15 
16     @Override
17     public void run() {
18         WebDownload wdl=new WebDownload();
19         wdl.download(url, name);
20         System.out.println(Thread.currentThread().getName());
21         
22     }
23     public static void main(String[] args) {
24         DownLoader2 dl1=new DownLoader2("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1237924924,3470614764&fm=26&gp=0.jpg","tupian/haitun.jpg");
25         DownLoader2 dl2=new DownLoader2("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1317686978,2345730812&fm=26&gp=0.jpg","tupian/laoshu.jpg");
26         DownLoader2 dl3=new DownLoader2("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2531381064,3648016782&fm=26&gp=0.jpg","tupian/tiger.jpg");
27         Thread t1=new Thread(dl1);
28         Thread t2=new Thread(dl2);
29         Thread t3=new Thread(dl3);
30         t1.start();
31         t2.start();
32         t3.start();
33         
34     }
35 
36 }

 

posted @ 2020-02-19 18:47  /*nobody*/  阅读(141)  评论(0编辑  收藏  举报