将线程级局部变量从一个类传递到另一个类



下面是场景。

public class A{
private final B b;
public A(){
this.b = new B();
this.c = new C();
}
public void setValue(){
this.b.value("HELLO WORLD")
this.c.print();
}
}

将"Hello World"设置为文本

public class B{
public volatile String text;
public B(){
this.text = "";
}
public void value(String t){
this.text = t;
}
}

无法获得"Hello World"。 它返回为">

public class C{
private final B b;
public B(){
this.b = new B;
}
public void print(){
System.out.println(this.b.text);
}
}

任何帮助将不胜感激。我需要一个解决方案将值传递给一个类到另一个类

我认为 B 构造函数内部的赋值导致了问题。由于您使文本易变,因此每次创建 B 实例时,文本的值都会被 " 覆盖,然后所有线程都将读取此更新的值。只需将文本变量设为静态,然后您就可以在 C 类中获得"Hello World"。

我得到了答案,必须将 B 的引用从 A 发送到 C

public class A{
private final B b;
private final C c;
public A(){
this.b = new B();
this.c = new C (this.b);
}
public void setValue(){
this.b.value("HELLO WORLD");
this.c.print();
}
}

public class B{
public volatile String text;
public B(){
this.text = "";
}
public void value(String t){
this.text = t;
}
}

public class C{
private final B b;
public C(B b){
this.b = b;
}
public void print(){
System.out.println(this.b.text);
}
}

最新更新