java 自旋锁

package spinlock;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockTest implements Runnable{
	private static int count = 0;
	private static SpinLock spinLock = new SpinLock();
	/**
	 * @param args
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		
		for (int i = 0; i < 100000; i++) {
			Thread thread = new Thread(new SpinLockTest());
			thread.start();
		}
		System.out.println("here");
		try {
			Thread.currentThread().sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(count);
	}
	
	@Override
	public void run() {
		spinLock.lock();
		count++;
		spinLock.unlock();
	}
}
/**
 * 自旋锁 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)。
 */
class SpinLock {
	
	private AtomicReference<Thread> sign = new AtomicReference<Thread>(); 

	public void lock() {
		Thread current = Thread.currentThread();
		System.out.println(Thread.currentThread().getName() + " wait");
		while (!sign.compareAndSet(null, current)) {
			
		}
	}
	
	public void unlock() {
		Thread current = Thread.currentThread();
		sign.compareAndSet(current, null);
	}
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。