public class Study {
public static void main(String[] args) {
ZixuanTest zixuanTest = new ZixuanTest();
//线程A持有5秒钟锁
new Thread(()->{
zixuanTest.lock();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
zixuanTest.unlock();
},"A").start();
//线程B自旋5秒后获得锁
new Thread(()->{
zixuanTest.lock();
zixuanTest.unlock();
},"B").start();
}
}
//资源类
class ZixuanTest{
AtomicReference<Thread> atomicReference = new AtomicReference<>();
//上锁
public void lock(){
System.out.println(Thread.currentThread().getName()+"jcome in");
while (!atomicReference.compareAndSet(null,Thread.currentThread())){
}
System.out.println(Thread.currentThread().getName()+"持有锁成功");
}
//释放锁
public void unlock(){
while(!atomicReference.compareAndSet(Thread.currentThread(),null)){
}
System.out.println(Thread.currentThread().getName()+"抛弃锁成功");
}
}
实现一个自旋锁
最新推荐文章于 2023-07-17 20:27:30 发布