多线程同步下载图片

package com.peanutist.day06;

import com.sun.xml.internal.bind.v2.model.runtime.RuntimePropertyInfo;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
//需要继承Thread类
public class TestThread01 extends Thread{

   public String url;
   public String file;
   TestThread01(String url,String file){
       this.url=url;
       this.file=file;
  }
   //重写Thread类的run方法
   public void run(){
       //调用下载方法
       new WebDownLoader().downLoader(this.url,this.file);
       System.out.println(this.file+"下载ok");
  }

   public static void main(String[] args) {
       TestThread01 file01 = new TestThread01("https://img2.doubanio.com/view/dale-online/dale_ad/public/bdc4648bae1f2ff.jpg", "file01");
       TestThread01 file02 = new TestThread01("https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2630627669.webp", "file02");
       TestThread01 file03 = new TestThread01("https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2629056068.webp", "file03");

       file01.start();
       file02.start();
       file03.start();

  }
}
//下载器
//一个class文件中只能有一个public类
//类没有参数
class WebDownLoader{

   //下载方法,参数:图片网址,下载后的存储名
   public void downLoader(String url,String file){
       try {
           //URL和File类的构造器参数都为String
           FileUtils.copyURLToFile(new URL(url),new File(file));
      } catch (IOException e) {
           e.printStackTrace();
      }
  }
}

 

posted on 2021-03-04 13:06  要给小八赚罐头钱  阅读(88)  评论(0)    收藏  举报