標籤:add val border number rup ber order cin 擷取
在Java中,synchronized是用來表示同步的,我們可以synchronized來修飾一個方法。也可以synchronized來修飾方法裡面的一個語句塊。那麼,在static方法和非static方法前面加synchronized到底有什麼不同呢?大家都知道,static的方法屬於類方法,它屬於這個Class(注意:這裡的Class不是指Class的某個具體對象),那麼static擷取到的鎖,是屬於類的鎖。而非static方法擷取到的鎖,是屬於當前對象的鎖。所以,他們之間不會產生互斥。
看代碼:
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
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(); }} |
運行結果是:
| 123456 |
function running...Static function running...function running...Static function running...function running...Static function running... |
那當我們想讓所有這個類下面的方法都同步的時候,也就是讓所有這個類下面的靜態方法和非靜態方法共用同一把鎖的時候,我們如何辦呢?此時我們可以使用Lock。
Java中synchronized用在靜態方法和非靜態方法上面的區別