ロックおよびロック解除された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スレッドの場合、Xunhua ++、10000回


100スレッドの場合、Xunhua ++、10000回


100スレッドの場合、Xunhua ++、100,000回


結果から、速度の順序は次のとおりです。AddThread3(ロックの競合が少ない)> AddThread1(比較と交換がわずかに多い)> AddThread2(ロックの競合が多い)

おすすめ

転載: blog.csdn.net/qq_31281327/article/details/79948817