尘封丶的博客

一日一AC

测试有锁与无锁CAS的性能

 出于对高并发的兴趣,对此做了个有锁与无锁CAS的性能测试

代码如下:

package bingFa_4;

import java.util.concurrent.atomic.AtomicInteger;

public class Test3 {
	static AtomicInteger sum1 = new AtomicInteger();
	static int sum2 = 0;
	static int sum3 = 0;
	static Object obj = new Object();
	//循环个数
	static int count = 10000; 
	
	//测试无锁的原子类
	public static class AddThread1 implements Runnable
	{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for(int k=0; k<count; k++)
				sum1.incrementAndGet();
		}
	}
	
	//测试在循环体内加锁
	public static class AddThread2 implements Runnable
	{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			for(int k=0; k<count; k++)
			{
				synchronized(obj)
				{
					sum2++;
				}
			}
		}
	}
	
	//测试在循环体外加锁
	public static class AddThread3 implements Runnable
	{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			synchronized(obj)
			{
				for(int k=0; k<count; k++)
					sum3++;
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		long start = System.currentTimeMillis();
		//线程数
		int thread_count = 10;
		
		Thread[] ts = new Thread[thread_count];
		for(int i=0; i<thread_count; i++)
		{
			ts[i] = new Thread(new AddThread1());
			ts[i].start();
		}
		for(int i=0; i<thread_count; i++)
			ts[i].join();
		long end = System.currentTimeMillis();
		System.out.println("CAS: \t\t"+(end-start) + " ms, sum1="+sum1 );
		
		start = System.currentTimeMillis();
		ts = new Thread[thread_count];
		for(int i=0; i<thread_count; i++)
		{
			ts[i] = new Thread(new AddThread2());
			ts[i].start();
		}
		for(int i=0; i<thread_count; i++)
			ts[i].join();
		end = System.currentTimeMillis();
		System.out.println("AddThread1,循环锁: "+(end-start)+ " ms, sum2="+sum2);
		
		start = System.currentTimeMillis();
		ts = new Thread[thread_count];
		for(int i=0; i<thread_count; i++)
		{
			ts[i] = new Thread(new AddThread3());
			ts[i].start();
		}
		for(int i=0;i<thread_count; i++)
			ts[i].join();
		end = System.currentTimeMillis();
		System.out.println("AddThread2,锁循环: "+(end-start)+ " ms,  sum3="+sum3);
	}
}


对于10个线程, 循化++,10000次


对于100个线程, 循化++,10000次


对于100个线程, 循化++,100000次


从结果来看, 速度快慢的顺序是: AddThread3(锁冲突很少)>AddThread1(比较和交换略多)>AddThread2(锁冲突多)

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31281327/article/details/79948817
文章标签: 多线程
个人分类: 多线程与并发编程
上一篇SSM框架之---Mybatis的学习笔记
下一篇JAVA-NIO的用法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭