java多线程(4):实现Runnable接口案例下载图片

本文介绍了一个使用Java多线程技术同时下载多个图片的示例程序。通过继承Thread类并实现Runnable接口,该程序能够并发地从指定URL下载图片,并利用Apache Commons IO库中的FileUtils类将图片保存到本地。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入pom

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

代码

package xiong.demo1;

import org.apache.commons.io.FileUtils;

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

public class TestThread2Download implements Runnable {

    private String url;

    private String name;

    public TestThread2Download(String url,String name){
        this.url = url;
        this.name = name;

    }

    public void run(){
        //下载图片
        TestThread2Download.WebDownloader webDownloader = new TestThread2Download.WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了图片-->"+name);
    }

    public static void main(String[] args){
        TestThread2Download t1 = new TestThread2Download("https://img-blog.csdnimg.cn/af0781733ad348d28d2d0d17bbcb8c2b.png","你好1.jpg");
        TestThread2Download t2 = new TestThread2Download("https://img-blog.csdnimg.cn/4063a22e5f114452a655a1c6bd787018.png","你好2.jpg");
        TestThread2Download t3 = new TestThread2Download("https://img-blog.csdnimg.cn/ced787d7ecff421d90d7c7ecdaa8472f.png","你好3.jpg");

        new Thread(t1).start();
        System.out.println("执行了t1");
        new Thread(t2).start();
        System.out.println("执行了t2");
        new Thread(t3).start();
        System.out.println("执行了t3");
    }


    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("downloader方法出现异常");
            }
        }
    }
}

运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不死鸟.亚历山大.狼崽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值