多线程实现网图下载:
package demo1;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class TestThread2 extends Thread{
private String url;
private String name;
public TestThread2(String url, String name) {
super();
this.url = url;
this.name = name;
}
@Override
public void run() {
// TODO Auto-generated method stub
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载文件名为:"+name+"的图片");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread2 thread1=new TestThread2("https://up.enterdesk.com/edpic_360_360/02/29/36/022936599db51ef9acb94f36bc83363c.jpg","明星.jpg");
TestThread2 thread2=new TestThread2("https://up.enterdesk.com/edpic_360_360/b5/e5/7b/b5e57baa62f92f49202e9179d3ba34ed.jpg", "迪丽热巴.jpg");
TestThread2 thread3=new TestThread2("https://up.enterdesk.com/edpic_360_360/ff/2e/64/ff2e64c0cf2e9fe665c2fac723ab0dbd.jpg","帅锅.jpg");
thread1.start();
thread2.start();
thread3.start();
}
}
//下载器
class WebDownloader {
public void downloader(String url,String name) {
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
实现效果: