2018年8月11日 星期六

ThreadLocal


public class Test {
    // private Map<Thread, Double> map = new HashMap<>();
    private ThreadLocal<Double> threadLocal = new ThreadLocal<>();
    
    public static void main(String[] args) {
        new Test().test();
    }
    
    private void test() {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                Double v = Math.random();
                System.out.println(Thread.currentThread().getName() + " 的 值 是 =" + v);
                // map.put(Thread.currentThread(), v);
                threadLocal.set(v);
    
                new innerAClass().ia();
                new innerBClass().ib();
            }).start();
    
        }
    }
    
    class innerAClass {
        public void ia() {
            // System.out.println(Thread.currentThread().getName() + "(a)取出的值是=" +
            // map.get(Thread.currentThread()));
            System.out.println(Thread.currentThread().getName() + "(a)取出的值是=" + threadLocal.get());
        }
    }
    
    class innerBClass {
        public void ib() {
            // System.out.println(Thread.currentThread().getName() + "(b)取出的值是=" +
            // map.get(Thread.currentThread()));
            System.out.println(Thread.currentThread().getName() + "(b)取出的值是=" + threadLocal.get());
        }
    }
}



沒有留言:

張貼留言