簡體   English   中英

將線程級局部變量從一個 class 傳遞到另一個

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

下面是場景。

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

任何幫助將不勝感激。 我需要一個解決方案將值傳遞給一個 class 到另一個

我認為 B 的構造函數內部的賦值導致了你的問題。 由於您使文本易失,因此每次創建 B 的實例時,文本的值都會被 "" 覆蓋,然后所有線程都將讀取此更新后的值。 只需將文本變量 static 設置為 class 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM