java并发计数器问题

来源:互联网 发布:男士风衣品牌 知乎 编辑:程序博客网 时间:2024/05/16 05:46
  1. package com.tongbanjie.trade.test.base;  
  2.   
  3. import java.util.concurrent.TimeUnit;  
  4. import java.util.concurrent.atomic.AtomicInteger;  
  5.   
  6. /** 
  7.  * 测试并发累加 
  8.  * @author huangqun 
  9.  * 
  10.  */  
  11. public class TestConcurrentPlusPlus {  
  12.   
  13.     public static int count = 0;  
  14.       
  15.     public volatile static int volatileCount = 0;  
  16.       
  17.     public static int synchronizedCount = 0;  
  18.       
  19.     public static AtomicInteger atomicCount = new AtomicInteger(0);  
  20.       
  21.     public volatile static AtomicInteger volatileAtomicCount = new AtomicInteger(0);  
  22.       
  23.     public static void main(String[] args) {  
  24.           
  25.         final Object lock = new Object();  
  26.           
  27.         for (int i = 0; i < 50000; i++) {  
  28.             new Thread(new Runnable() {  
  29.                   
  30.                 @Override  
  31.                 public void run() {  
  32.                     count++;  
  33.                     volatileCount++;  
  34.                       
  35.                     synchronized (lock) {  
  36.                         synchronizedCount++;  
  37.                     }  
  38.                       
  39.                     atomicCount.incrementAndGet();  
  40.                     volatileAtomicCount.incrementAndGet();  
  41.                 }  
  42.             }).start();  
  43.         }  
  44.           
  45.         // 休息5秒, 保证线程中的计算完成  
  46.         try {  
  47.             TimeUnit.SECONDS.sleep(5);  
  48.         } catch (InterruptedException e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.           
  52.         System.out.println("线程并发执行对计数器累计5000次,看并发结果!");  
  53.         System.out.println("count=" + count);  
  54.         System.out.println("volatileCount=" + volatileCount);  
  55.         System.out.println("synchronizedCount=" + synchronizedCount);  
  56.         System.out.println("atomicCount=" + atomicCount.get());  
  57.         System.out.println("volatileAtomicCount=" + volatileAtomicCount.get());  
  58.           
  59.     }