[英]Will instance objects in multiple threads have access to the same static class and variables?
If in my Main class I create an object like this: Tools tool = new Tools()
and inside the Tools
constructor I do this:如果在我的 Main class 中创建一个 object,如下所示: Tools tool = new Tools()
并在Tools
构造函数中执行以下操作:
Web web;
public Tools(){
web = new Web();
}
Will every thread's tools
object reference the same web?每个线程的tools
object 都会引用相同的 web 吗? I need them all to have a reference to a different Web
.我需要他们都引用不同的Web
。 Web is a static class that performs operations using a web driver which is why I need them all to be separate. Web 是一个 static class,它使用 web 驱动程序执行操作,这就是为什么我需要将它们全部分开。
Will every thread's tools object reference the same web?每个线程的工具 object 都会引用相同的 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.所有线程都可以访问相同的引用(前提是它们都可以访问相同的Tools
实例),但它们不一定会看到相同的值,因为根据 memory model 的可见性。
They would see the same value if you declared the web
member final
.如果您将web
成员声明为final
,他们将看到相同的值。
I need them all to have a reference to a different
Web
我需要他们都引用不同的Web
In that case you'd need to use a ThreadLocal<Web>
.在那种情况下,您需要使用ThreadLocal<Web>
。
ThreadLocal<Web> web = ThreadLocal.withInitial(Web::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.