public class MyLock {
static AtomicReference<Thread> atomicReference = new AtomicReference<>();
public static void myLock(){
System.out.println(Thread.currentThread().getName() + "进来了");
while (!atomicReference.compareAndSet(null,Thread.currentThread())){
System.out.println(Thread.currentThread().getName() + "wait...");
}
}
public static void myUnLock(){
System.out.println(Thread.currentThread().getName() + "出去了");
atomicReference.compareAndSet(Thread.currentThread(),null);
}
public static void main(String[] args) {
new Thread(()->{
myLock();
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
myUnLock();
},"a").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
myLock();
System.out.println(Thread.currentThread().getName());
myUnLock();
},"b").start();
}
}
a进来了
b进来了
bwait...
bwait...
bwait...
a出去了
bwait...
b
b出去了