赞
踩
自旋锁(spinlock):是指尝试去获取锁的线程不会立即阻塞,而是采用循环的方式去获取锁,这样的好处是减少线程上下文切换消耗,缺点是循环会消耗CPU。 (等待的时候还可以去处理其他任务)
- public final int getAndAddInt(Object var1, long var2, int var4) {
-
- int var5;
-
- do {
-
- var5 = this.getIntVolatile(var1, var2);
-
- } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
-
-
-
- return var5;
-
- }
- public class SpinlockDemo {
-
- // AtomicReference对象创建初始值为null
-
- private AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();
-
-
-
- public void lock() {
-
- Thread currentThread = Thread.currentThread();
-
- // 模拟自旋
-
- while(!threadAtomicReference.compareAndSet(null,currentThread)) {
-
-
-
- }
-
- System.out.println(Thread.currentThread().getName()+"\t get lock");
-
- }
-
-
-
- public void unLock(){
-
- Thread currentThread = Thread.currentThread();
-
- threadAtomicReference.compareAndSet(currentThread,null);
-
- System.out.println(Thread.currentThread().getName()+"\t release lock");
-
- }
-
-
-
- public static void main(String[] args) {
-
- SpinlockDemo spinlockDemo = new SpinlockDemo();
-
- // T1线程使用自旋方式获取锁,然后模拟5s业务处理
-
- new Thread(()-> {
-
- spinlockDemo.lock();
-
- try {
-
- System.out.println(Thread.currentThread().getName()+"\t开始模拟5s业务处理");
-
- TimeUnit.SECONDS.sleep(5);
-
- System.out.println(Thread.currentThread().getName()+"\t模拟5s业务处理完毕");
-
- } catch (InterruptedException e) {
-
- e.printStackTrace();
-
- }
-
- spinlockDemo.unLock();
-
- },"T1").start();
-
-
-
- // T1线程使用自旋方式获取锁,然后模拟3s业务处理
-
- new Thread(()-> {
-
- spinlockDemo.lock();
-
- try {
-
- System.out.println(Thread.currentThread().getName()+"\t开始模拟5s业务处理");
-
- TimeUnit.SECONDS.sleep(5);
-
- System.out.println(Thread.currentThread().getName()+"\t模拟5s业务处理完毕");
-
- } catch (InterruptedException e) {
-
- e.printStackTrace();
-
- }
-
- spinlockDemo.unLock();
-
- },"T2").start();
-
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。