Java多线程学习——图片下载

时间:2021-01-03 18:35:10

实现多线程方式1:继承类Thread——重写方法run——调用方法start

从网络下载图片首先要增加包commons-io.jar

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 下载图片
 */

public class WebDownLoader {

    /**
     * 下载工具
     * @param url
     * @param name
     */
    public void download(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
public class TDownloader extends Thread{
    String url;
    String name;

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

    @Override
    public void run() {
        WebDownLoader webDownLoader=new WebDownLoader();
        webDownLoader.download(url,name);
    }

    public static void main(String[] args) {
        TDownloader t1=new TDownloader("http://pic28.nipic.com/20130424/3822951_142421949000_2.jpg","photo1.jpg");
        TDownloader t2=new TDownloader("http://pic1.win4000.com/wallpaper/2018-01-23/5a669e431688c.jpg","photo2.jpg");
        TDownloader t3=new TDownloader("http://pic1.win4000.com/wallpaper/6/57a2ea76bcc06.jpg","photo3.jpg");

        t1.start();
        t2.start();
        t3.start();
    }
}

 实现多线程方式2:实现Runnable——重写run()方法——new Thread( 实现了Runnable接口的对象 ).start

下载工具类和上面一样,实现多线程的类变了

public class TDownloader implements Runnable{
    String url;
    String name;

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

    @Override
    public void run() {
        WebDownLoader webDownLoader=new WebDownLoader();
        webDownLoader.download(url,name);
    }

    public static void main(String[] args) {
        TDownloader t1=new TDownloader("http://pic28.nipic.com/20130424/3822951_142421949000_2.jpg","photo1.jpg");
        TDownloader t2=new TDownloader("http://pic1.win4000.com/wallpaper/2018-01-23/5a669e431688c.jpg","photo2.jpg");
        TDownloader t3=new TDownloader("http://pic1.win4000.com/wallpaper/6/57a2ea76bcc06.jpg","photo3.jpg");

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