实现ThreadLocal功能

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by lwc on 4/22/16.
 */
public class ThreadSharaDate {
    private static Map map = new HashMap<>();
    public static void main(String[] args) {
        for(int i=0;i<2;i++){
            new Thread(new Runnable(){
                public void run(){
                    int data = new Random().nextInt();
                    System.out.println("this is "+Thread.currentThread().getName()+"---"+data);
                    map.put(Thread.currentThread(), data);
                    new A().getDate();
                    new B().getDate();
                }
            }).start();
        }
    }

    static class A{
        public void getDate(){
            int date = map.get(Thread.currentThread());
            System.out.println("A thread is "+Thread.currentThread().getName()+"--" +date);
        }
    }

    static class B{
        public void getDate(){
            int date = map.get(Thread.currentThread());
            System.out.println("B thread is"+Thread.currentThread().getName()+"--" +date);
        }
    }
}

你可能感兴趣的:(Java)