java原子类:利用CAS自定义显示锁

/**
 * @Auther: Shen_hs
 * @Date: 2021/5/1 
 * @Description: 获取锁失败时的异常
 */
public class GetThreadException extends Exception {

    public GetThreadException() {
        super();
    }

    public GetThreadException(String message) {
        super(message);
    }
}
//======================================
/**
 * @Auther: Shen_hs
 * @Date: 2021/5/1 
 * @Description: 利用CAS自定义显示锁
 */
public class CompareAndSetLock {

    private final AtomicInteger value = new AtomicInteger(0);

    //表示被锁住的线程
    private Thread lockedThread;

    /**
     *  加锁
     */
    public void tryLock() throws GetThreadException {
        boolean success = value.compareAndSet(0, 1); //和期望值一样 返回true
        if(!success)
            throw new GetThreadException(Thread.currentThread().getName()+ " get the lock failed"); //与期望值不一样抛出异常
        else
            lockedThread = Thread.currentThread();
    }

    /**
     *  解锁
     */
    public void unLock(){
        if(0==value.get()){
            return;  //如果为0 不用解锁 直接返回
        }
        //只有锁住的线程为当前线程 才能解锁 避免被其他线程释放锁
        if(lockedThread == Thread.currentThread())
            value.compareAndSet(1,0); //解锁 将1变成0
    }
}
//=============================
public class AtomicIntegerTest2 {
    private static final CompareAndSetLock LOCK = new CompareAndSetLock();

    public static void main(String[] args) {
        IntStream.rangeClosed(0,5).forEach(i->new Thread(() -> {
            try {
                doSomething2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (GetThreadException e) {
                e.printStackTrace();
            }
        }).start());
    }



    public static void doSomething() throws InterruptedException {
        synchronized (AtomicIntegerTest2.class) {
            System.out.println(Thread.currentThread().getName()+" get the lock");
            Thread.sleep(10_000);
        }
    }

    public static void doSomething2() throws InterruptedException, GetThreadException {
        try {
            LOCK.tryLock();
            System.out.println(Thread.currentThread().getName()+" get the lock");
            Thread.sleep(10_000);
        } finally {
            LOCK.unLock();
        }
    }
}
//===========================OUTPUT(只有一个线程抢到锁 其他直接返回)
Thread-0 get the lock
com.wangwenjun.atomic.GetThreadException: Thread-2 get the lock failed
	at com.wangwenjun.atomic.CompareAndSetLock.tryLock(CompareAndSetLock.java:25)
	at com.wangwenjun.atomic.AtomicIntegerTest2.doSomething2(AtomicIntegerTest2.java:38)
	at com.wangwenjun.atomic.AtomicIntegerTest2.lambda$null$0(AtomicIntegerTest2.java:18)
	at java.lang.Thread.run(Thread.java:748)
com.wangwenjun.atomic.GetThreadException: Thread-4 get the lock failed
	at com.wangwenjun.atomic.CompareAndSetLock.tryLock(CompareAndSetLock.java:25)
	at com.wangwenjun.atomic.AtomicIntegerTest2.doSomething2(AtomicIntegerTest2.java:38)
	at com.wangwenjun.atomic.AtomicIntegerTest2.lambda$null$0(AtomicIntegerTest2.java:18)
	at java.lang.Thread.run(Thread.java:748)
com.wangwenjun.atomic.GetThreadException: Thread-5 get the lock failed
	at com.wangwenjun.atomic.CompareAndSetLock.tryLock(CompareAndSetLock.java:25)
	at com.wangwenjun.atomic.AtomicIntegerTest2.doSomething2(AtomicIntegerTest2.java:38)
	at com.wangwenjun.atomic.AtomicIntegerTest2.lambda$null$0(AtomicIntegerTest2.java:18)
	at java.lang.Thread.run(Thread.java:748)
com.wangwenjun.atomic.GetThreadException: Thread-3 get the lock failed
	at com.wangwenjun.atomic.CompareAndSetLock.tryLock(CompareAndSetLock.java:25)
	at com.wangwenjun.atomic.AtomicIntegerTest2.doSomething2(AtomicIntegerTest2.java:38)
	at com.wangwenjun.atomic.AtomicIntegerTest2.lambda$null$0(AtomicIntegerTest2.java:18)
	at java.lang.Thread.run(Thread.java:748)
com.wangwenjun.atomic.GetThreadException: Thread-1 get the lock failed
	at com.wangwenjun.atomic.CompareAndSetLock.tryLock(CompareAndSetLock.java:25)
	at com.wangwenjun.atomic.AtomicIntegerTest2.doSomething2(AtomicIntegerTest2.java:38)
	at com.wangwenjun.atomic.AtomicIntegerTest2.lambda$null$0(AtomicIntegerTest2.java:18)
	at java.lang.Thread.run(Thread.java:748)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值