英文:
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
吗?我希望它们都引用不同的Web
。Web
是一个使用网络驱动程序执行操作的静态类,这就是我需要它们都是独立的原因。
英文:
If in my Main class I create an object like this: Tools tool = new Tools()
and inside the Tools
constructor 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<Web>
.
ThreadLocal<Web> web = ThreadLocal.withInitial(Web::new);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论