java - java中的线程安全和实例

标签 java multithreading static thread-safety multiple-instances

我已经阅读了很多有关线程安全的内容,并且对对象的多个实例是否会影响线程安全感到困惑。下面举个例子来详细说明:
假设我们有一个名为 RGBColor 的类,用户可以设置红色、绿色和蓝色的值,然后返回颜色。

Public Class RGBColor {
    private int red;
    private int green;
    private int blue;
    Public RGBColor(int red, int green, int blue){
       this.red = red;
       this.green = green;
       this.blue = blue;
    }
    Public void setColor(int red, int green, int blue){
       this.red = red;
       this.green = green;
       this.blue = blue;
    }
    Public RGBColor getColor(){
       return this;
    }
}

现在,如果程序创建了该类的多个实例,例如:

RGBColor red = new RGBcolor(255,0,0);
RGBColor blue = new RGBcolor(0,0,255);

现在问题来了。这些类的实例是完全独立的吗?我的意思是线程安全会成为一个问题吗?毕竟,据我了解,它们应该是完全不同的对象,在 RAM 中具有不同的分配。

另一个问题是变量和方法是否是静态的,例如。

Public Class RGBColor {
    private static int RED;
    private static int GREEN;
    private static int BLUE;

    Public static void setColor(int red, int green, int blue){
       RED = red;
       GREEN = green;
       BLUE = blue;
    }
}

当涉及到线程安全时,如何处理静态变量和方法?

ps:我已经更新了第二个示例,因为它有缺陷。

最佳答案

Are these instances of the class are totally independent? I mean would thread safety would be an issue?

实例之间是独立的,是的。
线程安全问题是因为多个线程可能以并发方式访问一个实例,并且其中一个或两个线程对实例状态进行一些修改。

例如,假设您创建一个 RGBColor 实例,并且多个线程可以操作该实例。
现在,我们要求您 setColor() 调用不应与自身的其他调用交错。
在那里,你有一个竞争条件,你应该处理这个问题。
要处理它,您可以使用包围 setColor() 语句的 synchronized 语句,并使字段 volatile 以确保每个线程始终更新:

private volatile int red;
private volatile int green;
private volatile int blue;
...
public void setColor(int red, int green, int blue){
   synchronized (this){
     this.red = red;
     this.green = green;
     this.blue = blue;
   }
}

How are the static variables and methods would be handled when it comes to thread safety?

对于静态变量,与实例变量的方式相同。

对于实例方法,可以通过实例上的锁来实现线程安全。
对于静态方法,应该通过类本身的锁来实现。

关于java - java中的线程安全和实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908448/

相关文章:

python - 与其他代码并行执行 python Web 服务器

c++ - 如果线程分离,我是否需要终止它?

c# - 在 C# 中编写静态和非静态方法时如何避免 'call is ambiguous...' 错误?

c - C中文件范围内的可变修改数组

java - Spring MVC。未找到 HTTP 请求与 URI 的映射

java - 实体不匹配中的共享PK

java - Tic Tac Toe 程序中无法访问的代码

java - 使用 avro 序列化将整个 Json 发送到 kafka?

Python 多处理无法按预期与 Fuzzywuzzy 一起工作

java - 为什么java常量声明为静态的?