CAS的全称是Compare And Swap 即比较交换
TryLock实现类CompareAndSetLock.java
public class CompareAndSetLock {
private AtomicInteger value = new AtomicInteger(0);
private Thread threadLocal;
/**
* <p>get lock</p>
*/
public void tryLock() throws GetTryLockException {
boolean success = value.compareAndSet(0, 1);
if(!success){
throw new GetTryLockException("get lock fail");
}
this.threadLocal = Thread.currentThread();
}
/**
* <p>unlock</p>
*/
public void unlock(){
if(value.get() == 0){
return;
}
if(threadLocal == Thread.currentThread())
value.compareAndSet(1,0);
}
}
TryLock 测试类 TryLockTest.java
public class TryLockTest {
private static CompareAndSetLock lock = new CompareAndSetLock();
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(){
@Override
public void run() {
try {
doSomething();
} catch (GetTryLockException e) {
//e.printStackTrace();
System.out.println("get lock fail >>> do other thing.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
private static void doSomething() throws GetTryLockException, InterruptedException {
try {
lock.tryLock();
System.out.println(Thread.currentThread().getName()+" get lock success.");
Thread.sleep(100_0000);
}finally {
lock.unlock();
}
}
}
获取锁自定义异常类GetTryLockException.java
public class GetTryLockException extends Exception {
public GetTryLockException() {
super();
}
public GetTryLockException(String message) {
super(message);
}
}
运行结果
Thread-0 get lock success.
get lock fail >>> do other thing.
get lock fail >>> do other thing.
get lock fail >>> do other thing.
get lock fail >>> do other thing.
网友评论