image.png

    1. package com.pln.thread;
    2. import org.apache.commons.io.FileUtils;
    3. import java.io.File;
    4. import java.io.IOException;
    5. import java.net.MalformedURLException;
    6. import java.net.URL;
    7. public class TestThread2 extends Thread{
    8. private String url;
    9. private String name;
    10. // 构造方法给私有的变量赋值
    11. public TestThread2(String url,String name){
    12. this.name = name;
    13. this.url = url;
    14. }
    15. @Override
    16. public void run() {
    17. WebDownLoader webDownLoader = new WebDownLoader();
    18. try {
    19. webDownLoader.downloader(url,name);
    20. System.out.println("下载名字为:"+name);
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. System.out.println("run方法运行异常");
    24. }
    25. }
    26. public static void main(String[] args) {
    27. // 调用带参的构造方法
    28. TestThread2 t1 = new TestThread2("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20196302356495401.jpg","1.jpg");
    29. TestThread2 t2 = new TestThread2("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20196302342173219.jpg","2.jpg");
    30. TestThread2 t3 = new TestThread2("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20198310114727.jpg","3.jpg");
    31. t1.start();//开启线程
    32. t2.start();
    33. t3.start();
    34. }
    35. }
    36. //下载器
    37. class WebDownLoader{
    38. // 下载方法
    39. public void downloader(String url,String name) throws IOException {
    40. FileUtils.copyURLToFile(new URL(url),new File(name));
    41. }
    42. }