- 先看下面的代码
public static void main(String[] args) {
int threadNum;
System.out.println("The Multi thread results:");
threadNum = 5;
for (int i = 0; i < 5; i++) {
System.out.println("The " + (i + 1) + " Times Results:" + testAdd(threadNum));
}
}
static class TestTask implements Runnable {
private final ConcurrentHashMap<Integer, Integer> map;
public TestTask(ConcurrentHashMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
// synchronized (map) {
map.put(1, map.get(1) + 1);
// }
}
}
}
private static int testAdd(int threadNum) {
ConcurrentHashMap<Integer, Integer> map =
new ConcurrentHashMap<Integer, Integer>() {{
put(1, 0);
}};
ThreadPoolExecutor pool = new ThreadPoolExecutor(threadNum, threadNum, 2000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
// ExecutorService pool= Executors.newCachedThreadPool();
for (int i = 0; i < threadNum; i++) {
pool.execute(new TestTask(map));
}
pool.shutdown();
try {
pool.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return map.get(1);
}
执行效果:
The Multi thread results:
The 1 Times Results:1436098
The 2 Times Results:1498073
The 3 Times Results:1568226
The 4 Times Results:1350195
The 5 Times Results:1442906
可以看到每次执行的效果都不一样,我们期望的是累加的结果500万,可结果都比它小很多.
主要是这个代码 map.put(1, map.get(1) + 1);
为什么呢,因为ConcurrentHashMap只保证了put()或者get()的原子性---原子性就是要么同时成功,要么同时失败,不会被别的操作影响.
所以map.put(1, map.get(1) + 1);这个代码不是原子性的操作,它先拿到值,然后加1在put更新
单线程不会有任何问题,但是多线程会有以下可能.
线程A执行了get方法,还没执行put方法,然后这个时候线程B也执行了get方法,他们拿到的结果都是一样的,然后都执行了put方法,把
多线程中.因此,我们需要在关键代码处加锁才能保证这个代码的原子性
static class TestTask implements Runnable {
private final ConcurrentHashMap<Integer, Integer> map;
public TestTask(ConcurrentHashMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
synchronized (map) {//加锁,逻辑上让其成为原子性操作
map.put(1, map.get(1) + 1);
}
}
}
}
这样执行的结果就是理想值了
The Multi thread results:
The 1 Times Results:5000000
The 2 Times Results:5000000
The 3 Times Results:5000000
The 4 Times Results:5000000
The 5 Times Results:5000000