首先导入commons io.jar包
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; public class TestThread2 extends Thread{ //练习Thread,实现多线程同步下载图片 private String url;//网络图片地址 private String name;//保存的文件名 public TestThread2(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) { TestThread2 t1 = new TestThread2("", ""); TestThread2 t2 = new TestThread2("", ""); TestThread2 t3 = new TestThread2("", ""); 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异常"); } } }
通过使用静态变量和内部类实现参数传递,使用有参构造直接将url地址和下载的文件名传给downloader方法