当前位置 博文首页 > yuanting_的博客:Java多线程爬图片--Demo
package com.charper01;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Therad_Img implements Runnable {
//要爬的图片地址
public static String URL="http://style.iis7.com/uploads/2021/08/09480440404.jpg";
public static AtomicInteger count=new AtomicInteger(0);
public static void main(String[] args) {
Thread a=new Thread(new Therad_Img());
Thread b=new Thread(new Therad_Img());
Thread c=new Thread(new Therad_Img());
a.start();
b.start();
c.start();
}
public void run() {
Long start_time=System.currentTimeMillis();//开始时间
while(count.getAndAdd(1)<100){
System.err.println("这是第"+count.get()+"张图片");
ImgThared(count.get());
}
Long end_time=System.currentTimeMillis();//结束时间
System.err.println(end_time-start_time);
}
public void ImgThared(int imgName){
try {
URL url=new URL(URL);
//连接
URLConnection connection=url.openConnection();
//获取链接资源内容
InputStream inputStream=connection.getInputStream();
//要存储的地方
FileOutputStream outputStream=new FileOutputStream("C:\\Users\\HANNONG\\Desktop\\JavaImg\\"+imgName+".jpg");
byte[] bytes=new byte[1024];
while (inputStream.read(bytes)!=-1){
outputStream.write(bytes);
}
outputStream.close();
inputStream.close();
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
cs