構造器可以在 Java 中同步嗎?


,在 Java 中無法同步構造器。JVM 確保在給定時間點,只有一個執行緒可以呼叫構造器。這就是為什麼無需宣告構造器為synchronized並且在 Java 中是非法的。但是,我們可以在構造器內部使用synchronized 塊

如果我們嘗試在構造器之前放置synchronized關鍵字,編譯器會說“錯誤:此處不允許使用 synchronized 修飾符”。

示例

public class SynchronizedConstructorTest {
      // declaration of synchronized constructor
      public synchronized SynchronizedConstructorTest() {
         System.out.println("Synchronized Constructor");
      }
      public static void main(String args[]) {
         SynchronizedConstructorTest test = new SynchronizedConstructorTest();
      }
}

輸出

SynchronizedConstructorTest.java:3: error: modifier synchronized not allowed here
public synchronized SynchronizedConstructorTest() {
^
1 error

更新於: 02-Jul-2020

2K+ 次瀏覽

開啟你的 職業生涯

完成本課程即可獲得認證

開始吧
廣告