多个线程访问url

时间:2021-04-30 18:13:33

多个线程访问url

package com.aig.ecompassios.ecard;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import net.sf.json.JSONObject; public class EcardThread extends Thread {
static int i=0;
static String ebToken="";
static long time;
public EcardThread(int i,String ebToken){
this.i = i;
this.ebToken = ebToken;
}
public void run() {
String ecard="http://localhost:9080/";
long begintime = System.currentTimeMillis();
StringBuilder jsonECard = new StringBuilder();
try {
//ECard url
Thread.sleep(1000);
URL eCardURL = new URL(ecard+ebToken);
HttpURLConnection urlconECard = (HttpURLConnection)eCardURL.openConnection();
urlconECard.connect(); //获取连接
InputStream isECard = urlconECard.getInputStream();
BufferedReader bufferECard = new BufferedReader(new InputStreamReader(isECard,"UTF-8"));
String lECard = null;
while((lECard=bufferECard.readLine())!=null){
jsonECard.append(lECard);
}
System.out.println(jsonECard.toString());
System.out.println("Thread"+i+"执行时间为:"+(System.currentTimeMillis()-begintime)+"毫秒");
time+=(System.currentTimeMillis()-begintime);
System.out.println(time+"++++++");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
} public static void main(String[] args) {
long begintime = System.currentTimeMillis();
String ebToken = login();
/*for (int i = 0; i < 2; i++) {
EcardThread th = new EcardThread(i,ebToken);
th.start();
}*/
System.out.println(time+"=======");
while(time<0.3*60*1000){
EcardThread th = new EcardThread(i,ebToken);
th.start();
i=i+1;
}
System.out.println("总执行时间为:"+(System.currentTimeMillis()-begintime)+"毫秒");
}
}