标签:executors shm hello turn adp executor class ota public
Test类
public class Test { private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } }
非线程安全示例
import javax.annotation.concurrent.NotThreadSafe; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @NotThreadSafe public class HelloWorld { private static ConcurrentHashMap<String, Test> concurrentHashMap = new ConcurrentHashMap<>(); public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); final Test test = new Test(); concurrentHashMap.put("test", test); for(int i = 0; i < 50; i++) { executorService.execute(HelloWorld::increment); } } private static void increment() { concurrentHashMap.get("test").setA(concurrentHashMap.get("test").getA() + 1); System.out.println(concurrentHashMap.get("test").getA()); } }
打印结果
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
40
41
42
43
44
45
46
47
50
48
49
线程安全示例
import javax.annotation.concurrent.ThreadSafe; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @ThreadSafe public class HelloWorld { private static ConcurrentHashMap<String, Test> concurrentHashMap = new ConcurrentHashMap<>(); public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); final Test test = new Test(); concurrentHashMap.put("test", test); for(int i = 0; i < 50; i++) { executorService.execute(HelloWorld::increment); } } private static void increment() { synchronized (HelloWorld.class) { concurrentHashMap.get("test").setA(concurrentHashMap.get("test").getA() + 1); System.out.println(concurrentHashMap.get("test").getA()); } } }
打印结果
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
40
41
42
43
44
45
46
47
48
49
50
ConcurrentHashMap无法保证引用对象的线程安全
标签:executors shm hello turn adp executor class ota public
原文地址:https://www.cnblogs.com/aimul/p/10514462.html