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();
}
}
}