java線程--無鎖CAS(CompareAndSet比較交換)

無鎖線程安全整數

public class Test {
    static AtomicInteger ai = new AtomicInteger(0);
    static class MyTask implements Runnable {
        
        @Override
        public void run() {
            for(int i=0;i<10000;i++){
                ai.incrementAndGet();
            }

        }
        
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        MyTask t =new MyTask();
        //在線程池執行代碼,最終未能獲得正確答案
//        ExecutorService exs = Executors.newFixedThreadPool(10);
//        for(int i=0;i<10;i++){
//            exs.execute(t);
//        }
//
//        exs.shutdown();
//        System.out.println(ai);

        Thread[] ths = new Thread[10];
        for(int i =0;i<10;i++){
            ths[i] = new Thread(t);
        }
        for(int i =0;i<10;i++){
            ths[i].start();
        }
        for(int i =0;i<10;i++){
            ths[i].join();
        }
        System.out.println(ai);

    }

}

內部實現

public final int incrementAndGet() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }
    }

    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

AtomicReference<T> AtomicStampedReference<T>的理解

相關文章
相關標籤/搜索