天天看點

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------
           

這個核心思想就是線程安全的原子操作一定是線程安全的。