java自旋锁 发表于 2016-11-14 | | 热度 ℃ 此文章不涉及与互斥锁等比比较,只是单纯的介绍一个自旋锁,如果想要了解更多可以点击参考链接 一个自旋锁例子自旋锁的介绍原理等过程我就不在此介绍了,下面的参考已经写的非常不错了! 123456789101112131415161718192021222324252627282930313233343536373839/*** * 自旋锁 * @author Joker * */public class SpinLock { AtomicReference<Thread> owner = new AtomicReference<Thread>(); private int count ; public void lock() { Thread currentThread = Thread.currentThread(); System.out.println("lock() -> " + currentThread.getName()); if (currentThread == owner.get()) { count++; // 获取锁的次数 return ; } // 当线程越来越多由于while循环会浪费cpu时间片,compareAndSet需要多次对同一内存进行访问 while (!owner.compareAndSet(null, currentThread)) { } } public void unLock() { Thread currentThread = Thread.currentThread(); System.out.println("unLock() -> " + currentThread.getName()); if (currentThread == owner.get()) { if (count > 0) { count--; } else { owner.compareAndSet(currentThread, null); } } }} 1234567891011121314151617181920212223242526272829303132333435public class SpinLockTest implements Runnable{ static int sum ; private SpinLock lock; public SpinLockTest(SpinLock lock) { this.lock = lock; } public void run() { this.lock.lock(); this.lock.lock(); System.out.println("当前线程 " + Thread.currentThread().getName() + " start..."); sum++; System.out.println("当前线程 " + Thread.currentThread().getName() + " end..."); this.lock.unLock(); this.lock.unLock(); } public static void main(String[] args) throws InterruptedException { SpinLock lock = new SpinLock(); for (int i = 1; i < 5; i++) { SpinLockTest lockTest = new SpinLockTest(lock); Thread t = new Thread(lockTest, "thread-lock-"+i); t.start(); } Thread.sleep(1000); System.out.println(sum); }} 最后附上一张我自己画的一张运行图 参考http://www.cnblogs.com/cposture/p/SpinLock.html#_label0 人生苦短,我要打赏! 赏 微信打赏 支付宝打赏