多线程练习1_网图下载

### 案例:网图下载

```java
//1. 导入commons io里的jar包
//2. add as Library
package com.hao.Demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//多线程同步下载图片
public class TestThread extends Thread {

    private String url;
    private String name;

    public TestThread(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) {
        TestThread t1 = new TestThread("https://i0.hdslb.com/bfs/archive/0c6023b66b1e9c048095e99886a424b999bc8246.jpg","1.jpg");
        TestThread t2 = new TestThread("https://i0.hdslb.com/bfs/archive/33512603f27829b1279b59de5c725510973b17cf.jpg","2.jpg");
        TestThread t3 = new TestThread("https://i0.hdslb.com/bfs/archive/75b12ea49e8d7cc6cd2d0ada331f9851fe5ad27c.jpg","3.jpg");

        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异常,downloader方法出现问题");
        }
    }
}
posted @ 2021-02-09 16:13  多愚  阅读(57)  评论(0编辑  收藏  举报