用多线程实现一个数字的自增长到1000000,分别用无锁模式和锁模式来实现代码.

1.使用ReentrantLock.

package test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock; public class ThreadWithLock { private static final int THREAD_COUNT=3;
private static volatile int value= 0;
private static final ReentrantLock lock = new ReentrantLock();
private static final CountDownLatch startSignal = new CountDownLatch(1);
private static final CountDownLatch endSignal = new CountDownLatch(1); public static void main(String[] args) throws InterruptedException{ for(int i=0;i<=THREAD_COUNT;i++){
(new Counter()).start();
}
//start to record time.
long start = System.nanoTime();
//send the started signal to all threads.
startSignal.countDown();
//wait for anyone to finish the counting.
endSignal.await();
long end = System.nanoTime();
System.out.println(end-start);
} static class Counter extends Thread { @Override
public void run() {
try {
startSignal.await();
while(true){
try {
lock.lock();
if(value<1000000){
value++;
}
else {
break;
}
}
finally{
lock.unlock();
}
}
endSignal.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}

使用CAS模式,这其实是一种乐观锁模式,它默认是没有竞争的,如果存在竞争,失败了让代码重试.

package test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger; public class ThreadNoLock { private static final int THREAD_COUNT=3;
private static final AtomicInteger value= new AtomicInteger(0);
private static final CountDownLatch startSignal = new CountDownLatch(1);
private static final CountDownLatch endSignal = new CountDownLatch(1); public static void main(String[] args) throws InterruptedException{
for(int i=0;i<THREAD_COUNT;i++){
(new Counter()).start();
}
//start to record time.
long start = System.nanoTime();
//send the started signal to all threads.
startSignal.countDown();
//wait for anyone to finish the counting.
endSignal.await();
long end = System.nanoTime();
System.out.println(end-start);
} static class Counter extends Thread { @Override
public void run() {
try {
startSignal.await();
int current;
while(true){
if((current = value.get()) <1000000){
value.compareAndSet(current, current+1);
}
else{
break;
}
}
endSignal.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}

把Thread_count分别设置为1000,300,30,3 得到的性能数据如下,我们可以发现无锁模式的效率更高.

CAS实现无锁模式的更多相关文章

  1. 无锁模式的Vector

    这两天学习无锁的并发模式,发现相比于传统的 同步加锁相比,有两点好处1.无锁 模式 相比于 传统的 同步加锁  提高了性能 2.无锁模式 是天然的死锁免疫 下来介绍无锁的Vector--- LockF ...

  2. 使用CAS实现无锁的SkipList

    无锁 并发环境下最常用的同步手段是互斥锁和读写锁,例如pthread_mutex和pthread_readwrite_lock,常用的范式为: void ConcurrencyOperation() ...

  3. CAS无锁模式

    一.java内存模型:JMM 在内存模型当中定义一个主内存,所有声明的实例变量都存在于主内存当中,主内存的数据会共享给所有线程,每一个线程有一个块工作内存,工作内存当中主内存数据的副本当更新数据时,会 ...

  4. 使用CAS实现无锁列队-链表

    #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <iostream& ...

  5. 基于CAS实现无锁结构

    杨乾成 2017310500302 一.题目要求 基于CAS(Compare and Swap)实现一个无锁结构,可考虑queue,stack,hashmap,freelist等. 能够支持多个线程同 ...

  6. CAS 与 无锁队列

    http://coolshell.cn/articles/8239.html http://www.tuicool.com/articles/VZ3IBv http://blog.csdn.net/r ...

  7. CAS无锁机制原理

    原子类 java.util.concurrent.atomic包:原子类的小工具包,支持在单个变量上解除锁的线程安全编程 原子变量类相当于一种泛化的 volatile 变量,能够支持原子的和有条件的读 ...

  8. 锁、CAS操作和无锁队列的实现

    https://blog.csdn.net/yishizuofei/article/details/78353722 锁的机制 锁和人很像,有的人乐观,总会想到好的一方面,所以只要越努力,就会越幸运: ...

  9. CAS原子操作实现无锁及性能分析

    CAS原子操作实现无锁及性能分析 Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.csdn.net/chen19870707 ...

随机推荐

  1. jQuery 写的插件图片上下切换幻灯效果

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. Area Under roc Curve(AUC)

    AUC是一种用来度量分类模型好坏的一个标准. ROC分析是从医疗分析领域引入了一种新的分类模型performance评判方法. ROC的全名叫做Receiver Operating Character ...

  3. 转载--thinkphp框架的路径问题 - 总结

    转自:http://blog.sina.com.cn/s/blog_827ddd950100ulyv.html TP中有不少路径的便捷使用方法,比如模板中使用的__URL__,__ACTION__等, ...

  4. ubuntu + subversion + apache2 设置

    1.下载安装subversion,apache2 sudo apt-get updatesudo apt-get upgrade sudo  apt-get install apache2sudo a ...

  5. hadoop-1.2.1伪分布模式配置

    1.hadoop-env.sh 修改 export JAVA_HOME=/Library/Java/Home #增加 JAVA_HOME 2.masters localhost 3.slaves lo ...

  6. CSS兼容性(IE和Firefox)技巧大全

    CSS对浏览器的兼容性有时让人很头疼,或许当你了解当中的技巧跟原理,就会觉得也不是难事,从网上收集了IE7,6与Fireofx的兼容性处理技巧并整理了一下.对于web2.0的过度,请尽量用xhtml格 ...

  7. jQuery如何去判断页面是否有父页面?

    jQuery如何去判断页面是否有父页面?     是要判断当前页面是否被嵌入在frame里吗? 1 2 3 if (top != self) {     alert('我在框架里'); }

  8. 在Windows下部署安装hexo

    由于hexo的文档里并没有一步步详细写出过程的细节,在Windows下又更麻烦,所以就很容易入坑. 安装 安装github for windows,msysgit 安装包: https://githu ...

  9. [读书笔记]Mindset

    开始读 Mindset.准备开始记录读书笔记. Question: I know a lot of workaholics on the fast track who seem to have a f ...

  10. Visual Studio快捷键不能使用解决办法

    环境: Visual Studio 2010,windows 7 使用Visual Studio查找变量或方法时常用到[定位到]功能 但该功能的快捷键却不能使用,解决办法如下所示: 1.工具--> ...