天下之事,必先处之难,而后易之。

Java Map取值累加的线程安全问题

昨天在开发者头条上面看的一篇文章针对Map相关的线程安全讲解说的很好,今天根据思路还原了场景(隔壁老王半夜为何尖叫?这例子说的有点让老王很忙)。

Java代码:

package com.boonya.concurrent;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author PJL
 *
 * @note     功能描述:Add值的多线程安全问题--最优解方式是ConcurrentHashMap+Atomic*级别的原子操作
 * @package  com.boonya.concurrent
 * @filename AddConcurrent.java
 * @date     2019年4月23日 下午1:36:42
 */
public class AddConcurrent {
	
	/**
	 * HashMap非线程安全
	 * @throws InterruptedException
	 */
	public static void test0() throws InterruptedException{
		 HashMap<String, Integer> map = new HashMap<String,Integer>();
	     Integer integer = new Integer(1);
	     map.put("key", integer);
	     ExecutorService executorService = Executors.newFixedThreadPool(100);
	     for (int i = 0; i < 1000; i++) {
	         executorService.execute(new Runnable() {
	             @Override
	             public void run() {
	            	 map.put("key", map.get("key").intValue()+1) ;
	             }
	         });
	     }
	     Thread.sleep(3000); //模拟等待执行结束
	     System.out.println("test0()------" + map.get("key") + "------");
	     executorService.shutdown();
	}
	
	/**
	 * 严格线程安全的同步非原子操作--非线程安全
	 * @throws InterruptedException
	 */
	public static void test1() throws InterruptedException{
		 Hashtable<String, Integer> map = new Hashtable<String,Integer>();
	     Integer integer = new Integer(1);
	     map.put("key", integer);
	     ExecutorService executorService = Executors.newFixedThreadPool(100);
	     for (int i = 0; i < 1000; i++) {
	         executorService.execute(new Runnable() {
	             @Override
	             public void run() {
	            	 map.put("key", map.get("key").intValue()+1) ;
	             }
	         });
	     }
	     Thread.sleep(3000); //模拟等待执行结束
	     System.out.println("test1()------" + map.get("key") + "------");
	     executorService.shutdown();
	}
	
	/**
	 * 线程安全的非原子操作--非线程安全
	 * @throws InterruptedException
	 */
	public static void test2() throws InterruptedException{
		 ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String,Integer>();
	     Integer integer = new Integer(1);
	     map.put("key", integer);
	     ExecutorService executorService = Executors.newFixedThreadPool(100);
	     for (int i = 0; i < 1000; i++) {
	         executorService.execute(new Runnable() {
	             @Override
	             public void run() {
	            	 map.put("key", map.get("key").intValue()+1) ;
	             }
	         });
	     }
	     Thread.sleep(3000); //模拟等待执行结束
	     System.out.println("test2()------" + map.get("key") + "------");
	     executorService.shutdown();
	}
	
	/**
	 * 线程安全的原子操作--线程安全
	 * @throws InterruptedException
	 */
	public static void test3() throws InterruptedException{
		 ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String,AtomicInteger>();
	     AtomicInteger integer = new AtomicInteger(1);
	     map.put("key", integer);
	     ExecutorService executorService = Executors.newFixedThreadPool(100);
	     for (int i = 0; i < 1000; i++) {
	         executorService.execute(new Runnable() {
	             @Override
	             public void run() {
	                 map.get("key").incrementAndGet();
	             }
	         });
	     }
	     Thread.sleep(3000); //模拟等待执行结束
	     System.out.println("test3()------" + map.get("key") + "------");
	     executorService.shutdown();
	}
	
	public static void main(String[] args) throws InterruptedException {
		AddConcurrent.test0();
		AddConcurrent.test1();
		AddConcurrent.test2();
		AddConcurrent.test3();
    }


}

输出结果:

test0()------998------
test1()------998------
test2()------413------
test3()------1001------

这个核心思想就是线程安全的原子操作一定是线程安全的。

posted @ 2024-09-21 18:03  boonya  阅读(18)  评论(0)    收藏  举报  来源
我有佳人隔窗而居,今有伊人明月之畔。
轻歌柔情冰壶之浣,涓涓清流梦入云端。
美人如娇温雅悠婉,目遇赏阅适而自欣。
百草层叠疏而有致,此情此思怀彼佳人。
念所思之唯心叩之,踽踽彳亍寤寐思之。
行云如风逝而复归,佳人一去莫知可回?
深闺冷瘦独自徘徊,处处明灯影还如只。
推窗见月疑是归人,阑珊灯火托手思忖。
庐居闲客而好品茗,斟茶徐徐漫漫生烟。

我有佳人在水之畔,瓮载渔舟浣纱归还。
明月相照月色还低,浅近芦苇深深如钿。
庐山秋月如美人衣,画堂春阁香气靡靡。
秋意幽笃残粉摇曳,轻轻如诉画中蝴蝶。
泾水潺潺取尔浇园,暮色黄昏如沐佳人。
青丝撩弄长裙翩翩,彩蝶飞舞执子手腕。
香带丝缕缓缓在肩,柔美体肤寸寸爱怜。
如水之殇美玉成欢,我有佳人清新如兰。
伊人在水我在一边,远远相望不可亵玩。