旭日Follow_24 的CSDN 博客 ,全文地址请点击:
https://blog.csdn.net/xuri24/article/details/81293321
“高并发和多线程”总是被一起提起,给人感觉两者好像相等,实则 高并发 ≠ 多线程
多线程是完成任务的一种方法,高并发是系统运行的一种状态,通过多线程有助于系统承受高并发状态的实现
一,高并发与多线程
1,高并发:高并发不是JAVA的专有的东西,是语言无关的广义的,为提供更好互联网服务而提出的概念。高并发想让服务器(tomcat)能接受处理多用户多请求。
2,多线程:多线程只是为了达到高并发目的(首先得有多线程接收处理多任务,才有高并发发生)。在某个细节点上,为实现某并发功能而采用的一种具体的实现方法,这种功能也可以由多进程实现,
当然,也可以由多进程,多线程一起实现。这是战术上的并行。
总之:高并发是一种现象,多线程是一种Java提高性能的手段
其实就是用CountDownLatch来使多个线程同时运行,同时发送请求,虽然post的事件不能保证同时,但发post能保证同时(相差0.2毫秒),通过这种方法,测试了redis的setkey,getkey来保证不重复数据的时间阈值在几百纳秒,再短就算redis也无能为力了,所以多线程虽然快,但是没锁,还是不太安全。。
@Service
public class TestConcurrentService {
@Autowired
private ApiHttpClientService apiHttpClientService;
private static final Logger logger = Logger.getLogger(TestConcurrentService.class);
public void testConcurrent1(String sign) {
ExecutorService exec = Executors.newFixedThreadPool(3);
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
exec.execute(new HttpRequestUtils(begin, end, sign));
}
begin.countDown();
try {
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
exec.shutdown();
logger.info("main method end");
}
public class HttpRequestUtils implements Runnable {
private Logger log = Logger.getLogger(HttpRequestUtils.class);
private CountDownLatch begin;
private CountDownLatch end;
private String sign;
private String url = "http://localhost:8080/score/private/v1/injectsg";
public HttpRequestUtils(CountDownLatch begin, CountDownLatch end, String sign) {
this.begin = begin;
this.end = end;
this.sign = sign;
}
@Override
public void run() {
try {
begin.await();
Map<String, String> header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("sign", sign);
ScoreRequestBean bean = new ScoreRequestBean();
Data data = new Data();
data.setRemark("单发测试");
data.setExtId("ext111111519");
data.setPartnerMemberId(297);
data.setPoints(1);
bean.setData(data);
bean.setEventId("123asdasd");
System.out.println("线程" + Thread.currentThread().getName() +
"已接受命令," + "时间为:" + System.nanoTime() + "|" + System.nanoTime() / 1000000L);
apiHttpClientService.post(url, null, header, bean, ResultConstant.class);
System.out.println("线程" + Thread.currentThread().getName() +
"命令已结束");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
end.countDown();
}
}
}
}