API说明:(The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls)
- public class ShareData1 {
- //static int data = 0;
- static Map<Thread,Integer> map = new HashMap<Thread,Integer>();
- public static void main(String[] args) {
-
- for(int i=0;i<2;i++){
- new Thread(){
- public void run() {
- int data = new Random().nextInt();
- System.out.println(Thread.currentThread().getName()+":"+data);
- map.put(Thread.currentThread(), data);
- /* map.put(Thread.currentThread(), data);
- System.out.println(Thread.currentThread().getName()+":"+data);*/
-
- new A().getDataA();
- new B().getDataB();
- };
- }.start();
- }
- }
- static class A{
- void getDataA(){
- System.out.println(Thread.currentThread().getName()+"A:"+map.get(Thread.currentThread()));
- }}
- static class B{
- void getDataB(){
- System.out.println(Thread.currentThread().getName()+"B:"+map.get(Thread.currentThread()));
- }}
- }
-
- /*错误的结果:
- Thread-1:-236229789
- Thread-0:-934142735
- Thread-1A:null
- Thread-0A:-934142735
- Thread-1B:null
- Thread-0B:-934142735
- =====================
- Thread-0:-1331897743
- Thread-1:-1239048981
- Thread-1A:-1239048981
- Thread-0A:null
- Thread-1B:-1239048981
- Thread-0B:null
- ====================
- Thread-0:-1192204428
- Thread-1:-439715298
- Thread-0A:null
- Thread-1A:-439715298
- Thread-0B:null
- Thread-1B:-439715298
- ******************************************************
- 正确的结果
- Thread-0:1109365405
- Thread-1:969714427
- Thread-0A:1109365405
- Thread-1A:969714427
- Thread-0B:1109365405
- Thread-1B:969714427
- ===================
- Thread-1:1936099369
- Thread-0:-616837039
- Thread-0A:-616837039
- Thread-1A:1936099369
- Thread-0B:-616837039
- Thread-1B:1936099369
- */
复制代码 |
|