synchronized 修飾在 static方法和非static方法的區別

  Java中synchronized用在靜態方法和非靜態方法上面的區別java

  在Java中,synchronized是用來表示同步的,咱們能夠synchronized來修飾一個方法。也能夠synchronized來修飾方法裏面的一個語句塊。那麼,在static方法和非static方法前面加synchronized到底有什麼不一樣呢?你們都知道,static的方法屬於類方法,它屬於這個Class(注意:這裏的Class不是指Class的某個具體對象),那麼static獲取到的鎖,是屬於類的鎖。而非static方法獲取到的鎖,是屬於當前對象的鎖。因此,他們之間不會產生互斥。ide

  看代碼:對象

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();
	}
}

  運行結果是:blog

function running...
Static function running...
function running...
Static function running...
function running...
Static function running...

  那當咱們想讓全部這個類下面的方法都同步的時候,也就是讓全部這個類下面的靜態方法和非靜態方法共用同一把鎖的時候,咱們如何辦呢?此時咱們可使用Lock。同步

相關文章
相關標籤/搜索