研究synchronized底层实现,涉及到查看java字节码的需要

 

前提是,你的PC已经成功安装了JDK并别配置了环境变量。

==========查看方法=========

一.javap查看简约字节码方式

1.准备一个java文件

例如,文件所在目录在此处

 

Student.java文件内容如下:

package com.sxd.sweeping.test.synchron;

public class Student implements Runnable{

static int age;

public static synchronized void add(){

age++;

}

@Override

public void run() {

int size = 100000;

for (int i = 0; i < size; i++) {

add();

}

}

public static void main(String[] args) {

Thread thread1 = new Thread(new Student());

Thread thread2 = new Thread(new Student());

thread1.start();

thread2.start();

try {

thread1.join();

thread2.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Student.age);

}

}

View Code

 

 

2.CMD进入该目录下

 

 3.执行命令查看简约字节码信息

javap -c Student

 

报错提示:

找不到类

 

文末查看解决方法

 

4.查看到的简约字节码信息如下

 

 

 

 

 

 

二.查看java详细字节码信息

 

1.使用javap -verbose 命令查看详细字节码信息

javap -verbose Student

 

 

 

 

 

 

==========报错解决=========

1.javap查看字节码,提示找不到类

 

报错提示:

找不到类

 

 

解决方法:

先执行一次javac命令,在此处生成class文件后,再执行javap命令即可。

如下:

先执行

javac Student.java

再执行

javap -c Student

 

 

 

查看原文