对于非静态同步方法:如果使用synchronized关键字的话,锁对象是this
public class Test1 {
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
while(true) {
p.print1();
}
}
}.start();
new Thread() {
public void run() {
while(true) {
p.print2();
}
}
}.start();
}
}
class Printer{
public synchronized void print1() {//非静态同步方法
System.out.print("我");
System.out.print("是");
System.out.print("小");
System.out.print("仙");
System.out.print("女");
System.out.print("\r\n");
}
public void print2() {
synchronized(this) {//同步代码块,使用this锁对象
System.out.print("我");
System.out.print("爱");
System.out.print("学");
System.out.print("习");
System.out.print("\r\n");
}
}
而对于静态同步方法,由于静态方法优先于对象存在,所以锁对象不是this,而是该类的字节码对象(.class文件)
class Printer{
public static void print1() {
synchronized(Test1.class) {
System.out.println("同步代码块1");
}
}
public static void print2() {
synchronized(Test1.class) {
System.out.println("同步代码块2");
}
}
}