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 机制来实现加锁
来源: http://www.bubuko.com/infodetail-3093430.html