简体   繁体   English

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

[英]Passing thread level local variable from one class to another

Below is the scenario.下面是场景。

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();
   }
}

Setting "Hello World" to text将“Hello World”设置为文本

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

unable to get "Hello World".无法获得“Hello World”。 its coming back as ""它以“”的形式返回

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

Any Help will be appreciated.任何帮助将不胜感激。 I need a solution to pass value to one class to another我需要一个解决方案将值传递给一个 class 到另一个

I think the assignment inside the constructor of B is causing you the problem.我认为 B 的构造函数内部的赋值导致了你的问题。 As you have made text volatile so every time you create an instance of B, the value of text is overwritten by "" and then all thread will read this updated value.由于您使文本易失,因此每次创建 B 的实例时,文本的值都会被 "" 覆盖,然后所有线程都将读取此更新后的值。 Just make text variable static and then you can get the "Hello World" in class C.只需将文本变量 static 设置为 class C 中的“Hello World”即可。

I got the answer, have to send the reference of B to C from A我得到了答案,必须将 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM