解决并发下累计的问题

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());
		
	}
}

猜你喜欢

转载自825635381.iteye.com/blog/2293705