在Java中,是否可以确保变量的“read”将给出完全由同一线程写入该变量的值(在多个并发“write”操作的情况下)?
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‘object’的‘url’变量),这个值是同一线程在同一线程中‘config.getUrl()’之前写的(‘config.setUrl("someUrl")’发生在‘config.getUrl()之前)。
但是其他线程也有可能在同一时间调用config.setUrl("someOtherUrl")。
发布于 2021-06-24 21:46:04
使用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中的值将仅对该特定线程可用。
https://stackoverflow.com/questions/68116940
复制相似问题