闲话少说,代码
package juc;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicRefTest {
AtomicReference<Thread> ar = new AtomicReference<>(null);
public void myLock()
{
Thread thread = Thread.currentThread();
while(!ar.compareAndSet(null,thread))
{
//自旋锁
//System.out.println(ar.get().getName() + " cycling");
}
}
public void myUnLock()
{
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " unlock");
boolean b = ar.compareAndSet(thread, null);
}
}
class Test{
public static void main(String[] args) throws InterruptedException {
AtomicRefTest lock = new AtomicRefTest();
for (int i = 0; i < 20 ; i++) {
new Thread(()->{
lock.myLock();
try {
System.out.println(Thread.currentThread().getName()+ " working");
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.myUnLock();
}
}).start();
}
}
}