, 之前在面试的时候遇到了这个问题,没有理清楚相互之间的同步关系,现在有空记录下~
静态方法同步形式如: static synchronized method()
非静态方法同步形式如: synchronized method()
其中, 静态同步(static synchronized)锁定的对象是class,非静态方法同步锁定的对象是 当前对象(this)。
//方法1
public synchronized void method1() {
}
//方法2
public synchronized void method2() {
}
上面的方法1与方法2锁定的对象都是 this,不能同时执行。
//方法3
public static synchronized void method3() {
}
//方法4
public static synchronized void method4() {
}
也可以写成
public static void method4() {
synchronized (Demo.class) {
}
}
上面的方法3与方法4锁定的对象都是当前类,不能同时执行。 但是方法1(或者2) 与 方法3(或者4) 能够同时执行。
public class SynchronizedTest {
private static final String pattern = "HH:mm:ss";
public synchronized static void method1() {
DateFormat format = new SimpleDateFormat(pattern);
System.out.println("--method1 begin at: " + format.format(new Date()));
sleep(3);
System.out.println("--method1 end at: " + format.format(new Date()));
}
public synchronized static void method2() {
DateFormat format = new SimpleDateFormat(pattern);
System.out.println("--method2 begin at: " + format.format(new Date()));
sleep(3);
System.out.println("--method2 end at: " + format.format(new Date()));
}
public synchronized void method3() {
DateFormat format = new SimpleDateFormat(pattern);
System.out.println("--method3 begin at: " + format.format(new Date()));
sleep(3);
System.out.println("--method3 end at: " + format.format(new Date()));
}
public synchronized void method4() {
DateFormat format = new SimpleDateFormat(pattern);
System.out.println("--method4 begin at: " + format.format(new Date()));
sleep(3);
System.out.println("--method4 end at: " + format.format(new Date()));
}
private static void sleep(int secnonds) {
try {
Thread.sleep(secnonds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SynchronizedTest test = new SynchronizedTest();
new MyThread1().start();
new MyThread2().start();
new MyThread3(test).start();
new MyThread4(test).start();
}
static class MyThread1 extends Thread {
@Override
public void run() {
SynchronizedTest.method1();
}
}
static class MyThread2 extends Thread {
@Override
public void run() {
SynchronizedTest.method2();
}
}
static class MyThread3 extends Thread {
SynchronizedTest test;
public MyThread3(SynchronizedTest test) {
super();
this.test = test;
}
@Override
public void run() {
test.method3();
}
}
static class MyThread4 extends Thread {
SynchronizedTest test;
public MyThread4(SynchronizedTest test) {
super();
this.test = test;
}
@Override
public void run() {
test.method4();
}
}
}
执行上面的代码,结果如下:
--method3 begin at: 17:02:58
--method1 begin at: 17:02:58
--method3 end at: 17:03:01
--method4 begin at: 17:03:01
--method1 end at: 17:03:01
--method2 begin at: 17:03:01
--method4 end at: 17:03:04
--method2 end at: 17:03:04
以上结果可以看到:
1,method1(静态 synchronized) 与method3(非静态 synchronized)可以同时执行。
2,method1(静态 synchronized) 与method2(静态 synchronized) 不能同时执行。 3,method3(非静态 synchronized) 与method4(非静态 synchronized) 不能同时执行。