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="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564484358542&di=f008674adb2cd08bdd36a38e8c8f321b&imgtype=0&src=http%3A%2F%2Fi-3.391k.com%2F2018%2F8%2F14%2Fd4456c71-85d8-483c-b225-f04435066b5c.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();
}
}
}
Java多线程爬图片--Demo
最新推荐文章于 2021-11-28 13:20:40 发布