java并发计数器问题

  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.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值