面试时被问到:一个类包含两个被synchronized 修饰的static方法,是否会出现不同步的状态,一时没搞想明白,张口就说了句:会出现不同步的状态。
先做测试如下:
public class Test01 {
private static int i = 0 ;
public synchronized static void addI(){
i++ ;
System.out.println(Thread.currentThread().getName() + "add i: " + String.valueOf(i));
}
public synchronized static void reduceI(){
i-- ;
System.out.println(Thread.currentThread().getName() + "rest i : " + String.valueOf(i));
}
public static void main(String[] args) {
Thread _th01 = new Thread(new Runnable() {
@Override
public void run() {
while( true ){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Test01.addI();
}
}
}) ;
Thread _th02 = new Thread(new Runnable() {
@Override
public void run() {
while( true ){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Test01.reduceI();
}
}
}) ;
Thread _th03 = new Thread(new Runnable() {
@Override
public void run() {
while( true ){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
Test01.reduceI();
}
}
}) ;
_th01.start();
_th02.start();
_th03.start();
}
}
跟踪了大致3分钟的测试结果发现,是可以保持线程同步的。
原因:因为Test01.java中存在两个static方法,在java虚拟机中只会存在一个包含该静态方法的Test01实例,那么在方法上增加synchronized相当于对该实例本身增加锁,而synchronized本身为不可重入锁,因此是可以达到同步状态的