练习Thread,实现多线程同步下载图片

package com.guo.demo01;

import org.apache.commons.io.FileUtils;

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

/**
 * 练习Thread,实现多线程同步下载图片
 * @author  cg
 *
 * */
public class TestThread2 implements Runnable{

    private String url;//网络图片地址
    private String name;//保存的文件名

    //构造器
    public TestThread2(String url,String name){
        this.url = url;
        this.name = name;
    }

    //下载图片的线程执行体
    @Override
    public void run() {
        WebDownload webDownload = new WebDownload();
        webDownload.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://img-s.msn.cn/tenant/amp/entityid/AA1YWkc6.img?w=768&h=576&m=6&x=460&y=74&s=142&d=142","肖战.jpg");
        TestThread2 t2 = new TestThread2("https://inews.gtimg.com/news_bt/Onn7Sa3wKTQqo3UDXI-iGSb4A8LxJvyVsCO4plkYWaF4QAA/641","杨幂.jpg");
        TestThread2 t3 = new TestThread2("https://n.sinaimg.cn/sinakd10110/192/w1080h1512/20200701/ebaf-ivrxcex9280671.jpg","刘德华.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();


        }
    }


class WebDownload{
    //下载方法
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

posted @ 2026-03-23 10:42  果子同志  阅读(6)  评论(0)    收藏  举报