JAvaスレッドテスト高同時
3233 ワード
package com.expai.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
public class BingfaTest {
protected static final Logger LOG = Logger.getLogger(BingfaTest.class);
private static BingfaTest binfaTest = new BingfaTest();
public static BingfaTest getInstance() {
return binfaTest;
}
//count ,httpUrl url,para
public void exeThread(int count,String httpUrl,String para){
CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
ExecutorService executorService = Executors.newFixedThreadPool(count);
for (int i = 0; i < count; i++)
executorService.execute(new BingfaTest().new Task(cyclicBarrier,httpUrl,para));
// shutdown,
executorService.shutdown();
// ,executorService.isTerminated() true。
while (!executorService.isTerminated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Task implements Runnable {
private CyclicBarrier cyclicBarrier;
private String httpUrl;
private String para;
public Task(CyclicBarrier cyclicBarrier,String httpUrl,String para) {
this.cyclicBarrier = cyclicBarrier;
this.httpUrl=httpUrl;
this.para=para;
}
@Override
public void run() {
try {
//
cyclicBarrier.await();
//
URL url =new URL(httpUrl+para);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
//
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.print(para);
out.flush();
//
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line=null;
//
StringBuffer content = new StringBuffer();
while((line=in.readLine())!=null){
content.append(line);
}
in.close();
LOG.info(" ====="+content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}