实现Runnable接口,多线程下载照片练习

实现Runnable接口,多线程下载照片练习

代码及其注释:

package com.heima.Multithreading;

import org.apache.commons.io.FileUtils;

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

public class TestImplementRunnable implements Runnable {

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

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

    //下载图片的线程执行体
    @Override
    public void run() {
        //创建一个线程对象
        WebDownLoader2 webDownLoader2 = new WebDownLoader2();
        //调用start开启线程
        webDownLoader2.downLoad(url, name);
        System.out.println("文件下载成功,文件名为" + name);
    }

    //main主线程
    public static void main(String[] args) {
        TestImplementRunnable t1 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","1.jpg");
        TestImplementRunnable t2 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","2.jpg");
        TestImplementRunnable t3 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095805775?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","3.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}
//下载器
class WebDownLoader2{
    //下载方法
    public void downLoad(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downLoad方法下载出现问题");
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值