[英]Make data member accessible from all classes
I have a multi threaded application but there is one data member that needs to be accessed by many of the classes in the thread. 我有一个多线程应用程序,但是线程中的许多类都需要访问一个数据成员。
This data member would have a different value for each thread, but I want to access it without having to pass it as a parameter. 该数据成员对于每个线程将具有不同的值,但是我想访问它而不必将其作为参数传递。
How can this be done in Java? 用Java如何做到这一点?
I agree with the comment suggestion to use ThreadLocal. 我同意使用ThreadLocal的评论建议。 I think this program illustrates the sort of use you want: 我认为该程序说明了您想要的使用方式:
public class Test implements Runnable {
public static ThreadLocal<String> myString = new ThreadLocal<String>();
private String myInitialString;
public Test(String someString) {
myInitialString = someString;
}
public void run() {
myString.set(myInitialString);
System.out.println(myString.get());
myString.set(myString.get() + " changed");
System.out.println(myString.get());
new OtherTest().printTheString();
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[3];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Test("Thread" + i));
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
}
}
class OtherTest{
public void printTheString(){
System.out.println(Test.myString.get()+" OtherTest");
}
}
Typical output (the order varies from run to run): 典型输出(顺序因运行而异):
Thread0
Thread2
Thread2 changed
Thread1
Thread0 changed
Thread1 changed
Thread1 changed OtherTest
Thread0 changed OtherTest
Thread2 changed OtherTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.