synchronized在共享实例对象中线程安全
static synchronized在共享实例、非共享多实例对象均线程安全
代码
private synchronized void syncLock() {
while (++count < 10) {
System.out.println(count);
}
}
private static synchronized void staticSyncLock() {
while (++count < 10) {
System.out.println(count);
}
}
package com.lock.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ObjectLock {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
//sync修饰-同一对象(线程安全)
Lock lock = new Lock("sync");
for (int index = 1; index <= 10; index++) {
pool.execute(lock);
}
//sync修饰-不同对象(线程不安全)
for (int index = 1; index <= 10; index++) {
pool.execute(new Lock("sync"));
}
//sync+static修饰-不同对象(线程安全)
for (int index = 1; index <= 10; index++) {
pool.execute(new Lock("staticSync"));
}
pool.shutdownNow();
}
}
反编译
public synchronized void syncLock();
descriptor: ()V
flags: ACC_PUBLIC, ACC_SYNCHRONIZED
Code:
stack=2, locals=1, args_size=1
0: getstatic #5 // Field count:I
3: iconst_1
4: iadd
5: dup
6: putstatic #5 // Field count:I
9: bipush 10
11: if_icmpge 26
14: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
17: getstatic #5 // Field count:I
20: invokevirtual #7 // Method java/io/PrintStream.println:(I)V
23: goto 0
26: return
LineNumberTable:
line 26: 0
line 27: 14
line 29: 26
LocalVariableTable:
Start Length Slot Name Signature
0 27 0 this Lcom/lock/test/Lock;public static synchronized void staticSyncLock();
descriptor: ()V
flags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED
Code:
stack=2, locals=0, args_size=0
0: getstatic #5 // Field count:I
3: iconst_1
4: iadd
5: dup
6: putstatic #5 // Field count:I
9: bipush 10
11: if_icmpge 26
14: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
17: getstatic #5 // Field count:I
20: invokevirtual #7 // Method java/io/PrintStream.println:(I)V
23: goto 0
26: return
LineNumberTable:
line 32: 0
line 33: 14
line 35: 26
staticSyncLock()与syncLock()相比多ACC_STATIC标识。
总结
static修饰方法表明该方法为类级别方法,结合synchronized使用锁为类级。