CPU|java面试——常见的锁和锁升级( 三 )
mySpinLock.lock();
mySpinLock.unLock();
\"B\").start();
输出:
A got the lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
B try to get Lock
A want to Unlock
A Unlock
B got the lock
B want to Unlock
B Unlock
compareAndSet方法举例理解public class visit implements Runnable {
// private boolean someone = false;
private AtomicBoolean someone = new AtomicBoolean();
@Override
public void run() {
//它可以将引用与预期值(引用)进行比较 , 如果它们相等 , 则在AtomicReference对象内设置一个新的引用
if (someone.compareAndSet(false true)) {
System.out.println(Thread.currentThread().getName()
+ \": after judgmentthe someone is \" + someone);
try {
Thread.sleep(1 * 1000);
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(Thread.currentThread().getName()
+ \" i am coming\");
System.out.println(Thread.currentThread().getName()
+ \" i have to leaving\");
someone.set(false);
else {
System.out.println(Thread.currentThread().getName()
+ \" i can't visit the house\");
public static void main(String[
args) {
visit st = new visit();
new Thread(st \"thread_1\").start();
new Thread(st \"thread_2\").start();
输出结果
可以看出 , 当线程1执行期间 , 线程2是进不去的compareAndSet即 cas
备注:jvm只是一个协议 , 具体的实现有我很多:
描述一下对象在内存中的布局new 一个object对象 , main方法就是一个栈针 , 里面有一个object对象的引用 , 指向堆内存中的object对象
java object layout
- pom依赖
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
- 业务代码
public static void main(String[
args) {
int size = 10;
List<Integer> list = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
list.add(i);
//打印实例内部的占用
System.out.println(ClassLayout.parseInstance(list).toPrintable());
输出结果:offset起始位
对象头
- Java基础知识回顾,还记得吗?
- mybatis sharding-jdbc Java8日期
- 树莓派控制步进电机-TB6600-Java版本
- 德州点创教育JavaScript正则表达式授课大纲
- 如何编写JAVA小白第一个程序
- 英特尔推出新款四核CPU,目标直指Ryzen3 3300X
- 入门到老手全覆盖,锐龙CPU给3D创作加速
- java安全编码指南之:异常简介
- Java学习路线图
- Java核心技术点有哪些 有没有什么书籍推荐