cas lock-free optimization, spin lock, Atomic class

In my blog, I
test that volatile is not atomic. Is it necessary to add volatile to sysnchronized? Do you still need to add volatile if you
add sysnchronized? It is troublesome to add volatile and add sysnchronized. Can there be other ways?
Yes, we can achieve thread safety through cas operations


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * cas无锁优化,自旋锁   实例:Atomic类
 * 上一节我们讲到多个线程来操作count++的时候,需要加volatile和snychronized来保证线程的安全性
 * 这次我们用cas来保证线程安全
 */
public class CASDemo {
    
    
      //jdk自带的int类型的自增用AtomicInger是线程安全的
     AtomicInteger count=new AtomicInteger();

    public  void sumCount(){
    
    
        for (int i = 0; i <1000 ; i++) {
    
    
           count.incrementAndGet();
        }
    }

    public static void main(String[] args) {
    
    
        CASDemo t=new CASDemo();

        List<Thread> threads=new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
    
    
         threads.add(new Thread(() ->{
    
    
             t.sumCount();
            }));
        }

        threads.forEach((o)->{
    
    
            o.start();
        });

        threads.forEach((o)->{
    
    
            try {
    
    
                o.join();  //保证main线程到当前线程执行完成后再执行
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        });

        System.out.println(t.count);
    }
}

Guess you like

Origin blog.csdn.net/yanfei464486/article/details/112514810