在构造函数中使用synchronized块有什么用? [英] What is the use of synchronized block inside constructor?

查看:124
本文介绍了在构造函数中使用synchronized块有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们不能使构造函数 synchronized 但是可以在内部构造函数中编写 synchronized 。在什么情况下这样的要求会来?
我很开心。

We can not make constructor synchronized but can write synchronized this inside constructor. In what case such requirement will come ? I am amused.

package com.simple;
public class Test {
    public Test() {
        synchronized (this) {
            System.out.println("I am called ...");
        }
    }

    public static void main(String[] args) {
        Test test=new Test();   
        System.out.println(""+test);
    }

    @Override
    public String toString() {
        return "Test []";
    }
}


推荐答案

好,你可以在构造函数中启动一个新线程。这将是非常不寻常的 - 当然在您提供的代码中它将毫无意义 - 但它可能会发生。

Well, you could start a new thread within the constructor. It would be highly unusual - and certainly in the code you've provided it would be pointless - but it could happen.

语言通常不会尝试找到所有可能的你可以做的事情毫无意义 - 它会导致非常复杂的语言规范。语言用户也必须有一定程度的思考......

Languages don't typically try to find every possibly thing you could do that would be pointless - it would lead to a very complex language specification. There has to be some degree of thought on the part of the language users, too...

这篇关于在构造函数中使用synchronized块有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆