[英]Can we call synchronized method of an object inside the constructor of the object in Java?
I am new to Java. 我是Java新手。 I am wondering if it is possible to call a synchronized method inside constructor.
我想知道是否可以在构造函数中调用synchronized方法。 There is the example:
有一个例子:
class a{
int a1;
public a(){
a1 = 1;
increment();
}
private synchronized void increment(){
a1++;
}
}
It is a toy example. 这是一个玩具的例子。 I can just set the a1 to 2 at the constructor.
我可以在构造函数中将a1设置为2。 I am just confused whether we can call
increment()
inside the constructor or not. 我很困惑我们是否可以在构造函数中调用
increment()
。
You can do that but that synchronization is meaningless because the synchronized method will lock the instance that is currently being created. 您可以这样做,但同步没有意义,因为synchronized方法将锁定当前正在创建的实例。 But which other thread could access it while that has not still be created and returned ?
但是还没有创建并返回哪个其他线程可以访问它? No one.
没有人。
Constructors are indeed defacto thread safe as long as you follow good practices such as not passing this
to other classes/objects inside the constructor body. 只要你遵循良好的做法,例如不将
this
传递给构造函数体内的其他类/对象,构造函数确实是事实上的线程安全。
Your example could make more sense with a synchronized static
method or synchronized
on a static
field. 您的示例可以通过
synchronized static
方法更有意义,也可以在static
字段上synchronized
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.