我有一个多线程应用程序但是有一个数据成员需要被线程中的许多类访问。
这个数据成员对每个线程都有不同的值,但我想访问它而不必将其作为参数传递。
如何在Java中完成?
答案 0 :(得分:0)
我同意使用ThreadLocal的评论建议。我认为这个程序说明了你想要的那种用途:
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");
}
}
典型输出(订单因运行而异):
Thread0
Thread2
Thread2 changed
Thread1
Thread0 changed
Thread1 changed
Thread1 changed OtherTest
Thread0 changed OtherTest
Thread2 changed OtherTest