`
无量
  • 浏览: 1133894 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

解决并发下累计的问题

阅读更多
package com.tongbanjie.trade.test.base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试并发累加
 * @author huangqun
 *
 */
public class TestConcurrentPlusPlus {

	public static int count = 0;
	
	public volatile static int volatileCount = 0;
	
	public static int synchronizedCount = 0;
	
	public static AtomicInteger atomicCount = new AtomicInteger(0);
	
	public volatile static AtomicInteger volatileAtomicCount = new AtomicInteger(0);
	
	public static void main(String[] args) {
		
		final Object lock = new Object();
		
		for (int i = 0; i < 50000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					count++;
					volatileCount++;
					
					synchronized (lock) {
						synchronizedCount++;
					}
					
					atomicCount.incrementAndGet();
					volatileAtomicCount.incrementAndGet();
				}
			}).start();
		}
		
		// 休息5秒, 保证线程中的计算完成
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("线程并发执行对计数器累计5000次,看并发结果!");
		System.out.println("count=" + count);
		System.out.println("volatileCount=" + volatileCount);
		System.out.println("synchronizedCount=" + synchronizedCount);
		System.out.println("atomicCount=" + atomicCount.get());
		System.out.println("volatileAtomicCount=" + volatileAtomicCount.get());
		
	}
}

0
8
分享到:
评论
2 楼 无量 2016-05-04  
浅水明草 写道
楼主说一下这个在哪些场景可以使用

1. 高并发生成序列号 2. 并发计数器 3. 中间件 等很多场景要多这几个概念理解深入。这个只是写个demo,具体内容还没来的急写,接下来会完善这篇博客的
1 楼 浅水明草 2016-04-25  
楼主说一下这个在哪些场景可以使用

相关推荐

Global site tag (gtag.js) - Google Analytics