package com.thinker.common.thread.lock.spinLock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author lzh
 * 自己写的自旋锁，可重入。
 *
 * */
public class SpinLock{

	AtomicReference<Thread> own = new AtomicReference<Thread>();
	private int count = 0;

	public void lock(){
		Thread curr = Thread.currentThread();
		if(curr == own.get()){
			count ++;	return;
		}
		while(!own.compareAndSet(null,curr)){
			System.out.println(curr.getName());
		}
	}

	public void unlock(){
		Thread curr = Thread.currentThread();
		if(curr == own.get()){
			if(count > 0) 
				count -- ;
			else
			   own.compareAndSet(curr,null);	
		}
	}
	
}
