【问题标题】:Is it possible to read the value last written by same thread? [duplicate]是否可以读取同一线程最后写入的值? [复制]
【发布时间】:2021-09-08 00:26:42
【问题描述】:

在 Java 中是否可以确保变量的“读取”将给出由同一线程完全写入该变量的值(在多个并发“写入”操作的情况下)?

public class Client {
 private Config config;
 private RestClient client; 

 public void makeRequest() {
  client.post(config.getUrl(), requestEntity);
 }

 public void setConfig(Config config) {
  this.config = config; 
 }
}

我想确保' config.getUrl() '会给我准确的最后一个值('config'对象'的'url'变量)由同一线程前一段时间( config.setUrl(" someUrl") '发生在' config.getUrl() 在同一个线程中)。

但是有可能其他线程会同时调用config.setUrl("someOtherUrl")..

【问题讨论】:

    标签: java multithreading concurrency


    【解决方案1】:

    使用 ThreadLocal 存储线程特定的值。

    看看ThreadLocals

    例如,您可以像这样使用它们:

    ThreadLocal<String> threadLocalValue = new ThreadLocal<>();
    // Set the value of the url for this thread.
    threadLocalValue.set("someUrl");
    // Fetch the value again later like this.
    String someUrl = threadLocalValue.get();
    

    您存储在 ThreadLocal 中的值将仅适用于该特定线程。

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2013-06-10
      • 2020-02-20
      • 1970-01-01
      相关资源
      最近更新 更多