简体   繁体   English

我们可以在Java中调用对象构造函数内的对象的synchronized方法吗?

[英]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.

相关问题 我的构造函数中的JAVA Scanner对象,无法在我的方法中调用它 - JAVA Scanner object inside my constructor, cannot call it in my method Java同步块使用方法调用获取同步对象 - Java synchronized block using method call to get synch object 我们可以在Java中使用null对象调用静态方法吗? 如果是这样,怎么样? - Can we call a static method with a null object in Java? If so, how? Java - 我们可以在构造函数中声明对象变量吗? - Java - Can we declare object variable in constructor? 一个类的两个实例可以并行调用方法(在某个对象上同步) - Two instances of a class can call method (Synchronized on some object) parallelly Java:在另一个同步对象中同步对象 - Java: synchronize object inside another synchronized object Java同步方法锁定对象或方法? - Java synchronized method lock on object, or method? 我们可以在 null object 上调用任何方法吗? - can we call any method on null object? 当我们在方法内部创建锁(同步块)对象时会发生什么? - What will happen when we create lock (Synchronized block) object inside a method? 我们可以通过创建一个对象来调用类的所有构造函数吗 - Can we Call all constructor of a class by creating one object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM