不,构造函数无法在Java中同步。JVM确保在给定的时间点只有一个线程可以调用构造函数调用。这就是为什么,因为没有必要声明构造同步, 这是illega升 在Java中。但是,我们可以在构造函数中使用同步块。
如果我们试图在一个构造函数之前放置一个synced 关键字 ,则编译器会说“错误:这里不允许使用修饰符同步”。
public class SynchronizedConstructorTest {
//同步构造函数的声明
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