gpt4 book ai didi

java - 具有与输入处理方法分离的 setter/getter 的类是否可以被视为 "thread-safe"?

转载 作者:行者123 更新时间:2023-11-29 03:30:47 24 4
gpt4 key购买 nike

我正在阅读一本关于 Java 的书,其中有一个练习题,他们声明了一个带有一个私有(private)变量的类,一个公共(public) void 方法执行一些昂贵的操作来计算然后设置私有(private)变量变量,以及返回私有(private)变量的第二个公共(public)方法。问题是“如何使这个线程安全”,一个可能的答案是“同步两种方法中的每一个”,另一个可能的答案是“不能使这个类成为线程安全的”。

我想这个类不能成为线程安全的,因为即使你同步两个方法,你也可能会遇到 Thread1 调用 setter 并且在 Thread1 调用 getter 之前,Thread2 可能执行并调用 setter 的情况,所以当 Thread1 去检索结果时,它会得到错误的信息。这是看待事物的正确方式吗?书中建议的正确答案是可以通过同步这两种方法使该类成为线程安全的,现在我很困惑......

最佳答案

I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things?

你是对的。无法保证线程不会在您对每个方法的调用之间调用任何一个方法,从类中

如果你确实想这样做,那将需要一个包装器类。因此,如果带有 getter 和 setter 的类是这样的:

class Foo
{
private static int bar;

public static synchronized void SetBar(int z) { ... }
public static synchronized int GetBar() { ... }
}

包装类看起来像这样:

class FooWrapper
{

public synchronized int SetGetBar(int z)
{
Foo.SetBar(z);
return Foo.GetBar();
}

}

保证这会起作用的唯一方法是,如果你能保证所有调用都将通过你的包装类而不是直接到 Foo 类。

关于java - 具有与输入处理方法分离的 setter/getter 的类是否可以被视为 "thread-safe"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18393301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com