`
package spin;
import java.util.concurrent.atomic.AtomicReference;
public class spinDemo {
? ? AtomicReference<Thread> atomicReference = new AtomicReference<>();
? ? //加鎖
? ? public void myLock(){
? ? ? ? Thread thread = Thread.currentThread();
? ? ? ? //重點(diǎn) 使用CAS
? ? ? ? while (!atomicReference.compareAndSet(null, thread)){
? ? ? ? ? System.out.println(Thread.currentThread().getName()+"\t想拿到鎖");
? ? ? ? }
? ? ? ? System.out.println(Thread.currentThread().getName()+"\t拿到鎖");
? ? }
? ? //解鎖
? ? public void myUnLock(){
? ? ? ? Thread thread = Thread.currentThread();
? ? ? ? System.out.println(Thread.currentThread().getName()+"\t解鎖");
? ? ? ? atomicReference.compareAndSet(thread, null);
? ? }
}
`