利用atimicInteger cas的特性实现一个锁
主要是使用的是 atomicIntegerAPI 的compareAndSet()方法,让线程不在阻塞,获取不到直接失败.
我们先定义一个异常类
public class GetLockException extends Exception { public GetLockException() {
super();
} public GetLockException(String message) {
super(message);
}
}
锁实现类:
compareAndSet 主要就是对比,前面一个是期望值 后面一个是你要设置的值.
public class TryLockAtomic {
private static AtomicInteger value = new AtomicInteger(0); private Thread lockThread; public void tryLock() throws GetLockException {
boolean success = value.compareAndSet(0, 1);
if(!success){
throw new GetLockException("get lock failed");
}
lockThread = Thread.currentThread(); } public void unlock(){
if(0 == value.get()){return;} if(lockThread == Thread.currentThread()){
value.compareAndSet(1,0);
}
}
}
测试类
public static TryLockAtomic tryLockAtomic = new TryLockAtomic(); public static void main(String[] args) { for (int i = 0; i <2 ; i++) { new Thread(()->{
try {
dosomething2();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (GetLockException e) {
e.printStackTrace();
} }).start();
} } public static void dosomething() throws InterruptedException { synchronized (AtomicIntegerTest2.class){
System.out.println(Thread.currentThread().getName()+"---sleep");
Thread.sleep(1000000);
} } public static void dosomething2() throws InterruptedException, GetLockException { try { tryLockAtomic.tryLock();
System.out.println(Thread.currentThread().getName()+"---sleep");
Thread.sleep(1000000);
} finally {
//获取不到也会执行unlock 所以在这unlock 里判断是不是获取到锁的那个线程
tryLockAtomic.unlock(); }
}