玩转Java并发工具精通JUC成为并发多面手【15章完整版】 笔记汇总 模拟CAS操作,等价代码

299 阅读1分钟

对Java并发常见的工具类进行从使用到原理的详解, 包括CAS+AQS+ThreadLocal+ConcurrentHashMap+线程池+各种锁+并发综合实战项目

下载:链接:pan.baidu.com/s/1u6xXLnNU…  提取码:9voy 


package cas;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * 描述:     模拟CAS操作,等价代码
 */
public class TwoThreadsCompetition implements Runnable {

    private volatile int value;

    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectedValue) {
            value = newValue;
        }
        return oldValue;
    }

    public static void main(String[] args) throws InterruptedException {
        TwoThreadsCompetition r = new TwoThreadsCompetition();
        r.value = 0;
        Thread t1 = new Thread(r,"Thread 1");
        Thread t2 = new Thread(r,"Thread 2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(r.value);
    }

    @Override
    public void run() {
        compareAndSwap(0, 1);
    }
}

package cas;

\


/**

 * 描述:     模拟CAS操作,等价代码

 */

public class SimulatedCAS {

    private volatile int value;

\


    public synchronized int compareAndSwap(int expectedValue, int newValue) {

        int oldValue = value;

        if (oldValue == expectedValue) {

            value = newValue;

        }

        return oldValue;

    }

}

课程目录01.png

课程目录02.png