本帖最后由 WO.瘾姓埋銘 于 2014-5-11 10:13 编辑
- package threadTest;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- public class ThreadScopeShareData {
-
- 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
在这个代码中赋值之后,在类A和类B中获得当前线程的值时有可能是null这是为什么! |
|