如何使java类线程安全? [英] How to make java class thread safe?

查看:60
本文介绍了如何使java类线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的java类

I have a java class as below

 class User {

    String name;
    String phone;

    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }

}

这个类的使用方式是,对于每个线程,都会创建这个 User 类的 1 个对象.现在因为每个线程都有一个对象副本,我可以将这个类称为线程安全的吗?

The way this class is used is, for every thread 1 object of this User class is created. Now since there is one copy of object for every thread, can i call this class as thread safe?

我需要同步这些方法吗?

Do I need to synchronize these methods?

推荐答案

你呈现的方式,如果每个线程都有一个副本,那么它可以被称为线程安全的,因为最多访问一个线程.

The way you presented it, if each thread has its one copy, then it can be called thread-safe, as maximum of accessing threads is one.

>

另一件事 - 如果您将字段声明为 private 并将该类的实例创建为 final,那么它是不可变的(final User user = new User(...)).没有设置器,所以对象不能被修改,也不能改变它的引用.如果你想保持不变性,你必须让 setter 返回这个对象的一个​​新实例,并带有更改的字段.

Another thing - if you declare your fields as private and create the instance of that class as final, then it's immutable (final User user = new User(...)). There are no setters, so the object cannot be modified as well as it cannot change its reference. If you wanted to keep the immutability, you would have to make setters return a new instance of this object with changed fields.

@markspace 注意到,更好的方法是将字段声明为 final,因为如果您使用前一个并使 User 成为某个类的成员,它将不起作用(除非是 final).

@markspace noticed, that better approach would be to declare fields as final, because if you use the previous one and make User a member of some class, it won't work (unless final).

这篇关于如何使java类线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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