//在同一线程里的所有模块使用的是同一数据,其实下面代码就是ThreadLocal的原理,
//用这个就可以简单的实现,ThreadLocal的代码实现请看 java线程数据共享2
public class ThreadShareDataTest {
private static Map shareData = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread() {
public void run() {
int data = new Random().nextInt();
shareData.put(Thread.currentThread(), data);
System.out.println(Thread.currentThread().getName() + data);
System.out.println("moudle A in "
+ Thread.currentThread().getName() + new A().get());
System.out.println("moudle B in "
+ Thread.currentThread().getName() + new B().get());
}
}.start();
}
}
static class A {
public int get() {
return (Integer) shareData.get(Thread.currentThread());
}
}
static class B {
public int get() {
return (Integer) shareData.get(Thread.currentThread());
}
}
}