java線程數(shù)據(jù)共享1
//在同一線程里的所有模塊使用的是同一數(shù)據(jù),其實下面代碼就是ThreadLocal的原理,
//用這個就可以簡單的實現(xiàn),ThreadLocal的代碼實現(xiàn)請看 java線程數(shù)據(jù)共享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());
}
}
}