【JUC编程进阶】自旋锁
2021/6/2 20:21:11
本文主要是介绍【JUC编程进阶】自旋锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
自定义一个锁
:
package spinLock; import day3.A; import java.util.concurrent.atomic.AtomicReference; /** * @author admin * @version 1.0.0 * @ClassName demo1.java * @Description TODO * @createTime 2021年06月02日 19:37:00 */ // 自旋锁 public class demo1 { // Thread 默认为null AtomicReference<Thread> atomicReference = new AtomicReference<>(); // 加锁 public void mylock(){ Thread thread = Thread.currentThread(); System.out.println(Thread.currentThread().getName()+"------>mylock"); // 自旋锁 while (!atomicReference.compareAndSet(null,thread)){ } } // 解锁 public void myUnlock(){ Thread thread = Thread.currentThread(); System.out.println(Thread.currentThread().getName()+"------>myUnlock"); atomicReference.compareAndSet(thread,null); } }
测试:
package spinLock; import java.util.concurrent.TimeUnit; /** * @author admin * @version 1.0.0 * @ClassName Test.java * @Description TODO * @createTime 2021年06月02日 19:42:00 */ public class Test { public static void main(String[] args) throws Exception{ // 底层使用的自旋锁 CAS demo1 lock = new demo1(); new Thread(()->{ lock.mylock(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.myUnlock(); } },"T1").start(); TimeUnit.SECONDS.sleep(1); new Thread(()->{ lock.mylock(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.myUnlock(); } },"T2").start(); } }
这篇关于【JUC编程进阶】自旋锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享