自定义一个锁
:
package spinLock;
import day3.A;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author admin
* @version 1.0.0
* @ClassName demo1.java
* @Description TODO
* @createTime 2021年06月02日 19:37:00
*/
// 自旋锁
public class demo1 {
// Thread 默认为null
AtomicReference<Thread> atomicReference = new AtomicReference<>();
// 加锁
public void mylock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"------>mylock");
// 自旋锁
while (!atomicReference.compareAndSet(null,thread)){
}
}
// 解锁
public void myUnlock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"------>myUnlock");
atomicReference.compareAndSet(thread,null);
}
}
测试:
package spinLock;
import java.util.concurrent.TimeUnit;
/**
* @author admin
* @version 1.0.0
* @ClassName Test.java
* @Description TODO
* @createTime 2021年06月02日 19:42:00
*/
public class Test {
public static void main(String[] args) throws Exception{
// 底层使用的自旋锁 CAS
demo1 lock = new demo1();
new Thread(()->{
lock.mylock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnlock();
}
},"T1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(()->{
lock.mylock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnlock();
}
},"T2").start();
}
}