当前位置:网站首页>3.练习Thread

3.练习Thread

2022-08-09 09:23:00 过来我的小熊

Thread,网图下载

package com.xiancheng.demo;

import org.apache.commons.io.FileUtils;

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

// 练习Thread,实现多线程同步下载图片
// 继承Thread类
// 重写run()方法
// 运行start()方法
public class TestThread2 extends Thread{
    private String url; // 网络图片地址
    private String name; // 保存的文件地址

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

    public TestThread2() {

    }

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

    public static void main(String[] args) {
        TestThread2 testThread2 = new TestThread2("https://tse2-mm.cn.bing.net/th/id/OIP-C.2rQ25qnSMQHXGcHz3Rp2pAHaEo?w=277&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7","2.jpg");
        TestThread2 testThread3 = new TestThread2("https://tse2-mm.cn.bing.net/th/id/OIP-C.2rQ25qnSMQHXGcHz3Rp2pAHaEo?w=277&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7","3.jpg");
        TestThread2 testThread4 = new TestThread2("https://tse2-mm.cn.bing.net/th/id/OIP-C.2rQ25qnSMQHXGcHz3Rp2pAHaEo?w=277&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7","4.jpg");

        testThread2.start();
        testThread3.start();
        testThread4.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方法出现问题");
        }
    }
}

原网站

版权声明
本文为[过来我的小熊]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_56121715/article/details/123762571