一修壕、自定義鎖,繼承AbstractQueuedSynchronizer抽象類
/**
* @ClassName: com.example.redkapoktools.seckill.MyLock
* @Description:
* @Author: redkapok
* @Date: 2024/4/15 19:22
* @Version: v1.0
*/
public class MyLock extends AbstractQueuedSynchronizer {
private static final long serialVersionUID=1l;
@Override
protected boolean tryAcquire(int arg) {
if(compareAndSetState(0,1)){
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
if(getState()==0){
throw new IllegalStateException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
/**
* 獲取鎖
*/
public void lock(){
acquire(1);
}
/**
* 釋放鎖
*/
public void unlock(){
release(1);
}
/**
* 獲取鎖的狀態(tài)
* @return
*/
public boolean isLocked(){
return isHeldExclusively();
}
}
二角寸、并發(fā)測試
public class TestLock {
public static MyLock lock = new MyLock();
public static void main(String[] args) {
Runnable task=()-> {
System.out.println("Thread"+Thread.currentThread().getId()+"is trying to acquire the lock.!");
lock.lock();
System.out.println("Thread"+Thread.currentThread().getId()+"has acquired the lock.");
try{
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
System.out.println("Thread"+Thread.currentThread().getId()+"has released the lock.");
}
};
Thread t1=new Thread(task);
Thread t2=new Thread(task);
t1.start();
t2.start();
}
}