多線程下載圖片
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
/*
?* 下載圖片
?*/
public class WebDownloader {
?? ?
?? ?//下載的工具
?? ?public void download(String url,String name) {
?? ??? ?try {
?? ??? ??? ?FileUtils.copyURLToFile(new URL(url), new File(name));
?? ??? ?} catch (MalformedURLException e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("不合法的url");
?? ??? ?} catch (IOException e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("圖片下載失敗了");
?? ??? ?}
?? ?}
}
package cn.jd.thread;
public class TDownloader extends Thread {
?? ?private String url;//遠(yuǎn)程路徑
?? ?private String name;//存儲(chǔ)名字
?? ?
?? ?public TDownloader(String url, String name) {
?? ??? ?this.url = url;
?? ??? ?this.name = name;
?? ?}
?? ?@Override
?? ??? ?public void run() {
?? ??? ??? ?WebDownloader wd=new WebDownloader();
?? ??? ??? ?wd.download(url, name);
?? ??? ??? ?System.out.println(name);
?? ??? ?}
?? ?public static void main(String[] args) {
?? ??? ?//同時(shí)進(jìn)行,相互不干擾,沒(méi)有絕對(duì)的順序
?? ??? ?TDownloader? td1=new TDownloader("http://www.technosamrat.com/wp-content/uploads/2012/02/Ocean-Wallpapers-Images1.jpg", "1.jpg");
?? ??? ?TDownloader? td2=new TDownloader("http://pics.sc.chinaz.com/files/pic/pic9/201509/apic14546.jpg", "2.jpg");
?? ??? ?TDownloader? td3=new TDownloader("https://pic1.zhimg.com/v2-3b4fc7e3a1195a081d0259246c38debc_1200x500.jpg", "3.jpg");
?? ??? ?//啟動(dòng)3個(gè)線程
?? ??? ?td1.run();
?? ??? ?td2.run();
?? ??? ?td3.run();
?? ?}
?? ?
?? ?
?? ?
?? ?
?? ?
?? ?
?? ?
}
標(biāo)簽: