package Thread;
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; //联系Thread,实现多线程同步下载图片 public class threadDemo2 extends Thread { private String url;//网络图片地址 private String name;//保存的文件名 public threadDemo2(String url,String name){ this.url = url; this.name = name; } @Override public void run() { WebDownLoader webDownLoader = new WebDownLoader(); webDownLoader.downloader(url,name); System.out.println("下载了文件名为:"+name+"的文件"); } public static void main(String[] args) { threadDemo2 t1 = new threadDemo2("http://img.tuguaishou.com/ips_templ_preview/w432_q100/c5/f6/a7/lg_2559370_1572354908_5db83b5c038ec.jpg?auth_key=2239632000-0-0-6c120c2d0677dc637cb897b4e030d240", "1.jpg"); threadDemo2 t2 = new threadDemo2("http://img.tuguaishou.com/ips_templ_preview/w432_q100/f9/15/19/lg_3402655_1603039421_5f8c70bd859a6.jpg?auth_key=2239632000-0-0-12b2428b47e0b0163ba832a29b2a3951", "2.jpg"); threadDemo2 t3 = new threadDemo2("http://img.tuguaishou.com/ips_templ_preview/w432_q100/c5/f6/a7/lg_2559370_1572354908_5db83b5c038ec.jpg?auth_key=2239632000-0-0-6c120c2d0677dc637cb897b4e030d240", "3.jpg"); t1.start(); t2.start(); t3.start(); } } //下载器 class WebDownLoader{ //下载方法 public void downloader(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO异常,downloader方法出现问题!"); } } }
FileUtils是一个工具类,需要下载对应的包,百度搜即可;
最后结果:顺序是随机的;