码迷,mamicode.com
首页 > 编程语言 > 详细

ConcurrentHashMap无法保证引用对象的线程安全

时间:2019-03-12 09:13:55      阅读:213      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!