一、併發與高併發 概念
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++;
}
}