一、并发与高并发 概念
1、并发:
同时拥有两个或者多个线程,如果程序在单核处理器上运行,多个线程交替地换入或者换出内存,这些线程是同时“存在”的,每个线程都处于执行过程中的某个状态,如果运行在多核处理器上,此时,程序中的每个线程都将分配到一个处理器上,因此可以同时运行。
2、高并发
高并发(High Concurrency)是互联网分布式系统架构设计中必须考虑的因素之一,它通常是指,通过设计保证系统能够同时并行处理很多请求。
3、分析
- 并发:多个线程操作相同的资源,保证线程安全,合理使用资源
- 高并发:服务器同时处理很多请求,提高程序性能
二、案例
package com.example.overlap;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author haoxiansheng
* 并发简单案例计数器
*/
@Slf4j
public class CountExample {
private static int threadTotal = 200;
private static int clientTotal = 5000;
private static long count = 0;
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
log.info("e=>{}", e.getMessage());
}
});
}
executorService.shutdown();
log.info("count=>{}", count);
}
private static void add() {
count++;
}
}