CAS 构造锁compareAndSet

public class CASLock {
      //AtomicInteger是引用类型,final保证堆内存中地址不变,不保证栈内存中引用不改变
      private final AtomicInteger value= new AtomicInteger(0);
      //持有锁的线程才有权限解锁
      private Thread lockedThread;
     
      public void tryLock() throws Exception {
          boolean success = value.compareAndSet(0, 1);
          if(!success) {
              throw new Exception();
          }
          lockedThread=Thread.currentThread();
      }
     
      public void unLock() {
          if(0==value.get()) {
              return;
          }
          if(lockedThread==Thread.currentThread())
               value.compareAndSet(1,0);
      }
 }
 
 
 public static void main(String[] args) {
         CASLock casLock = new CASLock();
         
         for(int i=0;i<5;i++) {
             new Thread() {
                 @Override
                 public void run() {
                     while(true) {
                         try {
                             casLock.tryLock();
                             //业务逻辑
                             doSomething();
                         } catch (GetLockException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                         }finally{
                             casLock.unLock();}
                     }
                     }
             }.start();
       }
   }

 

学习来源:https://www.cnblogs.com/wushenghfut/p/11258767.html

posted @ 2020-09-01 16:39  小窝蜗  阅读(180)  评论(0)    收藏  举报