简体   繁体   English

多个线程中的实例对象会访问相同的 static class 和变量吗?

[英]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.

相关问题 通过多个线程访问静态实例的方法 - Access to methods of a static instance by multiple threads 在Java中,必须有一个带有共享变量的类,线程可以访问这些共享变量? - In Java, you must have a class with shared variables that threads will access? 匿名线程类无法访问非静态实例变量 - Anonymous thread class not able to access non static instance variables 如果多个线程访问相同的privarte方法,变量值会混合吗? - If Multiple threads access same privarte method, will the variables value get mixed? 具有相同可运行类的不同对象的多个线程可以重叠吗 - can multiple threads with different objects of same runnable class overlap 多个线程中的相同对象以进行同步 - Same objects in multiple Threads for Synchronization 接收器可以访问相同 class 的另一个实例的对象 - Sink having access to objects of another instance of same class 如果线程只能访问具有不同线程创建的具有自己实例的类的静态方法,则该线程将在哪个线程上执行? - If threads only can access static methods to a class with its own instance, created by a different thread, what thread will this execute on? 多个线程访问同一个文件 - Multiple threads access the same file 我们可以同时从多个线程访问同一个实例的同步方法和非同步方法吗? - Can we Access Synchronized method and an unsynchronized method of same instance from multiple threads at the same time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM