返回顶端

Java 多线程(一)网络资源下载

Java 多线程(一)网络资源下载

需引入外部包Common-io,百度可直接下载

package com.zzz.thread;

import org.apache.commons.io.FileUtils;

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

public class TestThread1 extends Thread{
    private String url;
    private String name;

    public TestThread1(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) {
        TestThread1 t1 = new TestThread1("https://www.kuangstudy.com/favicon.ico","threaddownload1.ico");
        TestThread1 t2 = new TestThread1("https://www.qq.com/favicon.ico","threaddownload2.ico");
        TestThread1 t3 = new TestThread1("https://www.kuangstudy.com/assert/images/doudizhu.jpg","threaddownload3.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-04-03 16:05  EEEEEEEric  阅读(52)  评论(0)    收藏  举报