Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction and example usage of java bias lock

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

本篇内容主要讲解"java偏向锁的介绍和实例用法",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"java偏向锁的介绍和实例用法"吧!

说明

1、要判断对象的MarkWord是否属于偏向模式。

如果不属于,进入轻量级锁判断逻辑。否则,继续下一步判断。

2、判断当前请求锁的线程ID是否与偏向锁本身记录的线程ID一致。

如果一致,继续下一步判断,如果不一致,跳转到步骤4;

3、判断是否需要重偏向。

重偏向逻辑将在下一节解释批量重偏向和批量撤销。如无需,直接获得偏向锁;

4、使用CAS算法更改对象的MarkWord。

将线程ID部分转换为线程ID,若更换成功,则重偏完成,获得偏向锁。若失败,则表明有多线程竞争,升级为轻量级锁。

实例

public class Demo2 { Object o = new Object(); //.c 文件打印出java threaid 对应的os threadid public native void tid(); static { System.loadLibrary("TestThreadNative"); } public static void main(String[] args) { //打印出主线程 System.out.println("java---java---java---java---java---java---java---java---java---"); Demo2 example4Start = new Demo2(); example4Start.start(); } public void start() { Thread t1 = new Thread() { @Override public void run() { while (true) { sync(); } } }; Thread t2 = new Thread() { @Override public void run() { while (true) { sync(); } } }; t1.setName("t1"); t2.setName("t2"); t1.start(); } public void sync() { synchronized (o) { // java threadid 是jvm给的线程id 并不是真是的os 对应的线程id // System.out.println(Thread.currentThread().getId()); //获取java thread 对应的真实的os thread 打印出id tid(); } }}到此,相信大家对"java偏向锁的介绍和实例用法"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report