多线程下载图片
多线程下载图片
以下代码从网上下载三张图片,使用3个线程,每个线程下载一张:
package com.cxf.multithread.download;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestForDownload {
public static void main(String[] args) {
MyThread myThread1 = new MyThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F11355207257%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636445046&t=47ce32847abf04e7b5b5f49f0d98729b","diga1.jpg");
MyThread myThread2 = new MyThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx1.sinaimg.cn%2Fmw690%2F0076Fpdqly1guvd1sr5v6j60et08cdg002.jpg&refer=http%3A%2F%2Fwx1.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636445491&t=f8933790c9614a327d3af045d452c778","diga2.jpg");
MyThread myThread3 = new MyThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.fxxz.com%2Fup%2F2021-1%2F16118024003330167.jpg&refer=http%3A%2F%2Fpic.fxxz.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636445613&t=7cf2449872dec9de14b101f66dcc772c","diga3.jpg");
myThread1.start();
myThread2.start();
myThread3.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方法出现问题");
}
}
}
class MyThread extends Thread{
private String url;
private String name;
public MyThread(String url,String name){
this.url = url;
this.name =name;
}
public void run(){
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件:" + name);
}
}
FileUtil来自于commons-io(已经写好的jar包,可从网上下载)。
输出结果:
下载了文件:diga2.jpg
下载了文件:diga3.jpg
下载了文件:diga1.jpg
按顺序开启线程,而线程不按开启顺序结束。