synchronized 修飾在 static方法和非static方法的區別
在Java中,synchronized是用來表示同步的,我們可以synchronized來修飾一個方法。也可以synchronized來修飾方法裏面的一個語句塊。那麼,在static方法和非static方法前面加synchronized到底有什麼不同呢?大家都知道,static的方法屬於類方法,它屬於這個Class(注意:這裏的Class不是指Class的某個具體對象),那麼static獲取到的鎖,是屬於類的鎖。而非static方法獲取到的鎖,是屬於當前對象的鎖。所以,他們之間不會產生互斥。
public class Demo {
public static synchronized void staticFunction()
throws InterruptedException {
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
System.out.println("Static function running...");
}
}
public synchronized void function() throws InterruptedException {
for (int i = 0; i <3; i++) {
Thread.sleep(1000);
System.out.println("function running...");
}
}
public static void main(String[] args) {
final Demo demo = new Demo();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
staticFunction();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
demo.function();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
運行結果是:
function running...
Static function running...
function running...
Static function running...
function running...
Static function running...
那當我們想讓所有這個類下面的方法都同步的時候,也就是讓所有這個類下面的靜態方法和非靜態方法共用同一把鎖的時候,我們如何辦呢?此時我們可以使用Lock。