使用原子类实现自定义加解锁

1.创建自定义加锁失败异常类

/**
 * 
 */
package com.gewb;

/**
 * 自定义加锁失败异常
 * @author Bingo.Ge
 * @date 2020年5月19日
 */
@SuppressWarnings("serial")
public class GetLockException extends Exception {
	
	public GetLockException() {
		
	}
	
	public GetLockException(String message) {
		super(message);
	}
}

2. 创建自定义加解锁类

/**
 * 
 */
package com.gewb;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义加解锁类
 * @author Bingo.Ge
 * @date 2020年5月19日
 */
public class CompareAndSetLock {
	private final AtomicInteger value = new AtomicInteger(0);
	
	/**
	 * 尝试加锁
	 * @throws GetLockException
	 */
	public void tryLock() throws GetLockException {
		boolean success = value.compareAndSet(0, 1);
		
		if(!success) {
			throw new GetLockException("Get the lock failed!");
		}
	}
	
	/**
	 * 尝试解锁
	 */
	public void unlock() {
		if(value.get() == 0) {
			return;
		} else {
			value.compareAndSet(1, 0);
		}
		
	}
	
	
}

 3.编写测试类

/**
 * 
 */
package com.gewb;

/**
 * 自定义加解锁测试
 * @author Bingo.Ge
 * @date 2020年5月19日
 */
public class AtomicIntegerTest2 {
	
	private final static CompareAndSetLock lock = new CompareAndSetLock();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		for(int i = 0; i < 200; i++) {
			new Thread() {
				@Override
				public void run() {
					try {
						doSomething2();
					} catch (GetLockException e) {
						System.out.println(Thread.currentThread().getName() + "get the lock failed!");
					}
				}
			}.start();
		}

	}
	
	/**
	 * 做一些加锁、解锁操作
	 * @throws GetLockException 
	 * @throws Exception
	 */
	private static void doSomething2() throws GetLockException {
		try {
			// 如果拿不到锁就抛异常
			lock.tryLock();
			System.out.println(Thread.currentThread().getName() + "get the locked!");
			Thread.sleep(1);
			// 没有异常才会解锁
			lock.unlock();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值