privatefinal ThreadLocal<Node> prev; privatefinal ThreadLocal<Node> node; privatefinal AtomicReference<Node> tail = new AtomicReference<Node>(new Node()); publicClhSpinLock(){ this.node = new ThreadLocal<Node>(){ protected Node initialValue(){ returnnew Node(); } }; this.prev = new ThreadLocal<Node>(){ protected Node initialValue(){ returnnull; } }; } publicvoidlock(){ final Node node = this.node.get(); node.locked = true; //一个CAS操作即可将当前线程对应的节点加到队列中, //并且同时获取前继节点的引用,然后等待前继节点释放锁 Node prev = this.tail.getAndSet(node); this.prev.set(prev); System.out.println(Thread.currentThread().getName() + " waiting for lock"); while(prev.locked){//进入自旋 } System.out.println(Thread.currentThread().getName() + " get the lock"); } publicvoidunlock(){ final Node node = this.node.get(); node.locked = false; this.node.set(this.prev.get()); System.out.println(Thread.currentThread().getName() + " releases the lock."); } privatestaticclassNode{ privatevolatileboolean locked; } publicstaticvoidmain(String[] args){ final ClhSpinLock lock = new ClhSpinLock(); lock.lock(); for(int i = 0; i < 10; i++){ new Thread(new Runnable(){ @Override publicvoidrun(){ lock.lock(); SleepUtils.mills(10); lock.unlock(); } },"Thread"+i).start(); } lock.unlock(); }
}
执行后输出结果为: main waiting for lock main get the lock Thread0 waiting for lock Thread3 waiting for lock Thread1 waiting for lock Thread4 waiting for lock Thread2 waiting for lock Thread7 waiting for lock main releases the lock. Thread0 get the lock Thread8 waiting for lock Thread5 waiting for lock Thread0 releases the lock. Thread9 waiting for lock Thread6 waiting for lock Thread3 get the lock Thread3 releases the lock. Thread1 get the lock Thread1 releases the lock. Thread4 get the lock Thread4 releases the lock. Thread2 get the lock Thread7 get the lock Thread2 releases the lock. Thread7 releases the lock. Thread8 get the lock Thread5 get the lock Thread8 releases the lock. Thread5 releases the lock. Thread9 get the lock Thread6 get the lock Thread9 releases the lock. Thread6 releases the lock.