Java高并发(1) 介绍

相关概念

并发知识点

  • 线程安全
  • 线程封闭
  • 线程调度
  • 同步容器
  • 并发容器
  • AQS
  • J.U.C

并发相关概念

多线程并发与线程安全

高并发解决思路与手段

  • 扩容
  • 缓存
  • 队列
  • 拆分
  • 服务降级与熔断
  • 数据库切库
  • 分库分表

高并发处理思路与手段

简单场景举例

简单计数

Demo 1 - CountExample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.mmall.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

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 exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
for (int i = 0; i < clientTotal; i++) {
exec.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
exec.shutdown();
System.out.println(count);
}

private static void add() {
count++;
}
}

使用线程池和信号量(Semaphore),使用整型计数。

输出结果:

1
2
3
4998

Process finished with exit code 0

每次输出结果都不一样

Demo 2 - MapExample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.mmall.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class MapExample {

private static int threadTotal = 200;
private static int clientTotal = 5000;

private static Map<Integer, Integer> map = new HashMap<>();

public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
for (int i = 0; i < clientTotal; i++) {
final int threadNmu = i;
exec.execute(() -> {
try {
semaphore.acquire();
func(threadNmu);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
exec.shutdown();
System.out.println(map.size());
}

private static void func(int threadNmu) {
map.put(threadNmu, threadNmu);
}

}

同样使用线程池和信号量(Semaphore),但使用Map计数。

输出结果:

1
2
3
4999

Process finished with exit code 0

每次输出结果都不一样

并发与高并发基本概念

并发

同时拥有两个或者多个线程,如果程序在单核处理器上运行,多个线程将交替地换入或者换出内容,这些线程是同时存在的,每个线程处于执行过程中的某个状态,如果运行在多核处理上时,程序中的每个线程都将分配到一个处理器核上,因此可以同时运行。

高并发(High Concurrency)

高并发是互联网分布式系统架构设计中必须考虑的因素之一,它通常是指,通过设计保证系统能够同时并行处理很多请求。

比较

  • 并发: 多个线程操作相同的资源,保证线程安全,合理使用资源
  • 高并发: 服务能同时处理很多请求,提高程序性能

涉及知识点

基础知识与核心知识

并发及并发的线程安全处理

高并发处理的思路及手段

知识技能

  • 基础框架: Spring Boot, Maven, JDK8, MySQL
  • 基础组件: Mybatis, Guava, Lombok, Redis, Kafka
  • 高级类: Joda-Time, Atomic包, J.U.C, AQS, ThreadLoacl, RateLimiter, Hystrix, threadPool, shardbatis, curator, elastic-job…

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2021 朝着牛逼的道路一路狂奔 All Rights Reserved.

访客数 : | 访问量 :