有时需要测试一下某个成果的并发机能,又不要想借助于其他东西,索性就本身的开拓语言,来一个并发请求就最利便了。
Java 中模仿并发请求,自然是很利便的,只要多开几个线程,提倡请求就好了。可是,这种请求,一般会存在启动的先后顺序了,算不得真正的同时并发!怎么样才气做到真正的同时并发呢?是本文想说的点,Java 中提供了闭锁 CountDownLatch, 恰好就用来做这种事就最符合了。
只需要:
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
public class LatchTest {
public static void main(String[] args) throws InterruptedException {
Runnable taskTemp = new Runnable() {
// 留意,此处长短线程安详的,留坑
private int iCounter;
@Override
public void run() {
for(int i = 0; i < 10; i++) {
// 提倡请求
// HttpClientOp.doGet("https://www.baidu.com/");
iCounter++;
System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
LatchTest latchTest = new LatchTest();
latchTest.startTaskAllInOnce(5, taskTemp);
}
public long startTaskAllInOnce(int threadNums, final Runnable task) throws InterruptedException {
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNums);
for(int i = 0; i < threadNums; i++) {
Thread t = new Thread() {
public void run() {
try {
// 使线程在此期待,当开始门打开时,一起涌入门中
startGate.await();
try {
task.run();
} finally {
// 将竣事门减1,减到0时,就可以开启竣事门了
endGate.countDown();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
};
t.start();
}
long startTime = System.nanoTime();
System.out.println(startTime + " [" + Thread.currentThread() + "] All thread is ready, concurrent going...");
// 因开启门只需一个开关,所以立马就开启开始门
startGate.countDown();
// 等等竣事门开启
endGate.await();
long endTime = System.nanoTime();
System.out.println(endTime + " [" + Thread.currentThread() + "] All thread is completed.");
return endTime - startTime;
}
}
其执行结果如下图所示:

HttpClientOp 东西类,可以利用 成熟的东西包,也可以本身写一个扼要的会见要领,参考如下:
class HttpClientOp {
public static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回功效字符串
try {
// 建设长途url毗连工具
URL url = new URL(httpurl);
// 通过长途url毗连工具打开一个毗连,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 配置毗连方法:get
connection.setRequestMethod("GET");
// 配置毗连主机处事器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 配置读取长途返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection毗连,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 封锁资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 封锁长途毗连
}
return result;
}
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过长途url毗连工具打开毗连
connection = (HttpURLConnection) url.openConnection();
// 配置毗连请求方法
connection.setRequestMethod("POST");
// 配置毗连主机处事器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 配置读取主机处事器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向长途处事器传送数据/写数据时,需要配置为true
connection.setDoOutput(true);
// 默认值为:true,当前向长途处事读取数据时,昆山软件开发,配置为true,该参数无关紧要
connection.setDoInput(true);
// 配置传入参数的名目:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 配置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通过毗连工具获取一个输出流
os = connection.getOutputStream();
// 通过输出流工具将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过毗连工具获取一个输入流,昆山软件开发,向长途读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流工具举办包装:charset按照事情项目组的要求来配置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 轮回遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 封锁资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与长途地点url的毗连
connection.disconnect();
}
return result;
}
}
如上,就可以提倡真正的并发请求了。
并发请求操纵流程示意图如下:
