javap -verbose -p 显示私有成员,方法的命令
public class MyTest2 {
String str = "Welcome";
private int x = 5;
public static Integer in = 10;
public void setX(int x) {
this.x = x;
}
public static void main(String[] args) {
MyTest2 myTest2 = new MyTest2();
myTest2.setX(8);
in = 20;
}
}
不加不打印x信息
命令加p显示int x
方法改为private亦然
给setX方法加锁:
private synchronized void setX(int x) {
this.x = x;
}
private synchronized void setX(int);
descriptor: (I)V
flags: ACC_PRIVATE, ACC_SYNCHRONIZED 多出一个访问修饰符
Code:
stack=2, locals=2, args_size=2
0: aload_0
1: iload_1
2: putfield #4 // Field x:I
5: return
LineNumberTable:
line 16: 0
line 17: 5
LocalVariableTable:
Start Length Slot Name Signature
0 6 0 this Lcom/yshuoo/jvm/bytecode/MyTest2;
0 6 1 x I
一般加了synchronized字节码会有moniterenter,moniterexit两个命令,这里没有是因为修饰的方法,所以隐掉了。
编写一个对对象上锁的synchronzied,进锁只有一个,但是出锁因为正常返回,异常等,会有多个
private void test(String str){
synchronized (this.object){
System.out.println("hello world");
}
}
private void test(java.lang.String);
descriptor: (Ljava/lang/String;)V
flags: ACC_PRIVATE
Code:
stack=2, locals=4, args_size=2
0: aload_0
1: getfield #6 // Field object:Ljava/lang/Object;
4: dup
5: astore_2
6: monitorenter
7: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
10: ldc #8 // String hello world
12: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
15: aload_2
16: monitorexit
17: goto 25
20: astore_3
21: aload_2
22: monitorexit
23: aload_3
24: athrow
25: return
Exception table:
from to target type
7 17 20 any
20 23 20 any
LineNumberTable:
line 22: 0
line 23: 7
line 24: 15
line 25: 25
LocalVariableTable:
Start Length Slot Name Signature
0 26 0 this Lcom/yshuoo/jvm/bytecode/MyTest2;
0 26 1 str Ljava/lang/String;
StackMapTable: number_of_entries = 2
frame_type = 255 /* full_frame */
offset_delta = 20
locals = [ class com/yshuoo/jvm/bytecode/MyTest2, class java/lang/String, class java/lang/Object ]
stack = [ class java/lang/Throwable ]
frame_type = 250 /* chop */
offset_delta = 4
private synchronized static void test2(){
}
对静态方法加锁是给MyTest2所对应的Class对象上锁