import java.util.concurrent.atomic.AtomicReference;
public class T7 {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + " lock");
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void unLock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName() + " unlock");
}
public static void main(String[] args) {
T7 t7 = new T7();
new Thread(new Runnable() {
@Override
public void run() {
t7.myLock();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t7.unLock();
}
},"a").start();
new Thread(new Runnable() {
@Override
public void run() {
t7.myLock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t7.unLock();
}
},"b").start();
}
}
运行结果: