package com.Lock;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLock {
AtomicReference<Object> reference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"这是我的加锁");
while (!reference.compareAndSet(null,thread)){
}
}
public void unMyLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"这是我的解锁");
reference.compareAndSet(thread,null);
}
}
package com.Lock;
import java.util.concurrent.TimeUnit;
public class SpinLockTest {
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
new Thread(()->{
try {
spinLock.myLock();
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}finally {
spinLock.unMyLock();
}
},"A1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
try {
spinLock.myLock();
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}finally {
spinLock.unMyLock();
}
},"A2").start();
}
}