package com.test; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Manual write a spinlock * @Author renyahui * */ public class SelfCircleLock { //原子引用线程 AtomicReference<Thread> atomicReference=new AtomicReference<Thread>(); public void myLock(){ Thread thread=Thread.currentThread(); System.out.println (Thread.getName () + "\ t Come in ......" ); the while (atomicReference.compareAndSet (! Null {, the Thread)) // System.out.println ( "self-locking rotation ... ... "); } } public void myUnLock(){ Thread thread=Thread.currentThread(); System.out.println(thread.getName()+"\t invoke myunlock……"); while(!atomicReference.compareAndSet(thread, null)){ System.out.println ( "self-unlocking rotation ......" ); } } public static void main(String[] args) { final SelfCircleLock selfCircle=new SelfCircleLock(); new Thread( new Runnable() { public void run() { selfCircle.myLock(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace (); } selfCircle.myUnLock(); } }).start(); try { Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new Thread( new Runnable() { public void run() { selfCircle.myLock(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace (); } selfCircle.myUnLock(); } }).start(); } }