首页 > 文章列表 > 在Java中,构造函数可以被同步吗?

在Java中,构造函数可以被同步吗?

同步 Java中的构造函数 构造函数同步
227 2023-08-19

,在Java中,构造函数不能被同步。JVM确保在任何给定时间点只有一个线程可以调用构造函数。这就是为什么不需要将构造函数声明为同步的,在Java中这是非法的。但是,我们可以在构造函数内部使用同步块

如果我们试图在构造函数前面加上同步关键字,编译器会报错“错误:不允许在此处使用修饰符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