private static Map<Thread, Integer> map = new HashMap<Thread, Integer>();
public static void main(String[] args) {
//实现两个线程共享一个数据
for(int i=0; i<2; i++) {
new Thread(new Runnable(){
@Override
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + "get data :" + data);
map.put(Thread.currentThread(), data);
A.getData();
B.getData();
}
}).start();
}
}
static class A {
public static void getData() {
System.out.println("A from " + Thread.currentThread().getName() + "get data :" + map.get(Thread.currentThread()));
}
}
static class B {
public static void getData() {
System.out.println("B from " + Thread.currentThread().getName() + "get data :" + map.get(Thread.currentThread()));
}
}
}
复制代码
输出结果如下:
Thread-1get data :1474835009
Thread-0get data :521348174
A from Thread-1get data :null
A from Thread-0get data :521348174
B from Thread-1get data :null
B from Thread-0get data :521348174