package demo1;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread2 extends TestThread{
private String url;
private String name;
public TestThread2(String url,String name) {//在有参构造中传入参数,为实例变量初始化值
this.url = url;
this.name = name;
}
@Override
public void run() {//重写run()方法
WebDownloader webDownloader = new WebDownloader();
webDownloader.Download(url,name);
System.out.println("下载类文件名为:"+name);
}
public static void main(String[] args) {
//挨个创建对象并且执行构造方法
TestThread2 t1 = new TestThread2("https://www.apple.com.cn/v/imac-24/e/images/overview/colors_lifestyle_fallback__fat816a51hua_large.jpg","p1.jpg");
TestThread2 t2 = new TestThread2("https://img1.baidu.com/it/u=3855106272,1253404534&fm=253&fmt=auto&app=138&f=JPEG?w=678&h=500","p2.jpg");
TestThread2 t3 = new TestThread2("https://img1.baidu.com/it/u=3252704542,3882037568&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500","p3.jpg");
//加入线程,并发执行run()方法
t1.start();
t2.start();
t3.start();
}
}
//下载类
class WebDownloader{
public void Download(String url,String name){
try {//使用FileUtils.copyURLToFile方法将url下的图片保存至文件
FileUtils.copyURLToFile(new URL(url),new File(name));//快捷键option+command+t调出代码包裹
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
标签:TestThread2,url,网图,String,new,多线程,public,下载,name
From: https://www.cnblogs.com/qt0312/p/16787635.html