簡體   English   中英

Java中繼承下的同步靜態方法行為

[英]Synchronized static methods behaviour under inheritance in java

我在某處閱讀:

如果靜態同步方法位於不同的類中,則一個線程可以在每個類的靜態同步方法中執行。 每個類一個線程,無論它調用哪種靜態同步方法。

假設我有下面的類層次結構:

public class Base {
    public static synchronized void printBase() {
        System.out.println("Inside Base");
    }
}

public class Derived extends Base {
    public static synchronized void printDerived() {
        System.out.println("Inside Derived");
    }
}

1)如果我有以下兩個函數調用:

Base.printBase();
Derived.printDerived();

據我了解,它們不應互相阻塞,並且兩者可以同時執行。 由於調用是用不同的類進行的。

2)但是,如果我有以下兩個函數調用:

Derived.printBase();
Derived.printDerived();

由於它們在同一類上被調用,因此應相互阻止。 對?

還是還有其他東西?

不,您在第2點中描述的行為不是您所看到的。

同步對象取決於方法的聲明位置,而不取決於方法的調用方式。 JLS 8.3.4.6開始

對於類(靜態)方法,使用與該方法的類的Class對象關聯的監視器。

這里的“方法類”是Base.classprintBase ,以及Derived.classprintDerived 因此,代碼大致相當於:

public class Base {
    public static void printBase() {
        synchronized (Base.class) {
            System.out.println("Inside Base");
        }
    }
}

public class Derived extends Base {
    public static void printDerived() {
        synchronized (Derived.class) {
            System.out.println("Inside Derived");
        }
    }
}

因此,無論如何調用,這兩種方法都可以從不同的線程中調用,而不會互相阻塞。 (當然,如果其中一個線程已經擁有Derived.class的監視器,那將防止其他線程調用printDerived等-我只是在談論這些方法如何相互影響。)

兩種情況都不會導致線程被阻塞。 只有兩個線程調用printBase才會引起阻塞。

在第二種情況下:

Derived.printBase();
Derived.printDerived();

Derived.printBase(); 實際上是對Base.printBase();的調用Base.printBase();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM