java中cas的使用


CAS是compare and swap的缩写,即我们所说的比较交换。cas是一种基于锁的操作,而且是乐观锁。

在java中锁分为乐观锁和悲观锁

synchronized就是一种悲观锁(独占锁),会导致其它所有需要锁的线程挂起,等待持有锁的线程释放锁。

而乐观锁采取了一种宽泛的态度,通过某种方式不加锁来处理资源,比如通过给记录加version来获取数据,性能较悲观锁有很大的提高

//代码转自 https://blog.csdn.net/u011381576/article/details/79922538

@Test
public void testCas() throws InterruptedException {
for (int i = 1; i <= 3; i++) {
MyThrend thrend = new MyThrend("thead" + i);
Thread thread = new Thread(thrend);
thread.start();
}
Thread.sleep(2000);
System.out.println(MyCount.count.get());
}

static class MyThrend implements Runnable {
private String name;
MyThrend(String threadName) {
this.name = threadName;
}

@Override
public void run() {
for (int i=0;i<20;i++){
MyCount.count.getAndIncrement(); //加1方法
System.out.println(name+"*"+MyCount.count.get());
}

}
}

private static class MyCount {
static AtomicInteger count = new AtomicInteger(0);
}

//java.util.current.atomic包下面,采用了CAS机制来实现加锁


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM