实例对象在多线程中是否可以访问相同的静态类和变量?

huangapple go评论95阅读模式
英文:

Will instance objects in multiple threads have access to the same static class and variables?

问题

如果在我的主类中像这样创建一个对象:Tools tool = new Tools(),并且在Tools构造函数内部执行以下操作:

Web web;
public Tools(){
    web = new Web();
}

那么每个线程的tools对象引用的是同一个web吗?我希望它们都引用不同的WebWeb是一个使用网络驱动程序执行操作的静态类,这就是我需要它们都是独立的原因。

英文:

If in my Main class I create an object like this: Tools tool = new Tools() and inside the Toolsconstructor I do this:

Web web;
public Tools(){
    web = new Web();
}

Will every thread's tools object reference the same web? I need them all to have a reference to a different Web. Web is a static class that performs operations using a web driver which is why I need them all to be separate.

答案1

得分: 2

每个线程的工具对象是否引用相同的网络?

所有线程将可以访问相同的引用(前提是它们都可以访问相同的Tools实例),但它们不一定会看到相同的值,这是由于内存模型中的可见性导致的。

如果你将web成员声明为final,它们会看到相同的值。

我需要让它们都引用不同的 Web 对象。

在这种情况下,你需要使用 ThreadLocal<Web>

ThreadLocal<Web> web = ThreadLocal.withInitial(Web::new);
英文:

> Will every thread's tools object reference the same web?

All threads will have access to the same reference (provided they all have access to the same instance of Tools), but they won't necessarily see the same value, because of visibility in terms of the memory model.

They would see the same value if you declared the web member final.

> I need them all to have a reference to a different Web

In that case you'd need to use a ThreadLocal&lt;Web&gt;.

ThreadLocal&lt;Web&gt; web = ThreadLocal.withInitial(Web::new);

huangapple
  • 本文由 发表于 2020年9月1日 23:22:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63690667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定