初看TheadLocal 与其子类 InheritableThreadLocal

ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
InheritableThreadLocal 的特点是 子线程能获取到父线程的 变量
 1 public class ThreadLocalTest {
 2 
 3     static class TestThread implements Runnable {
 4 
 5         ThreadLocal<Map<String, Integer>> local;
 6         ThreadLocal<Map<String, Integer>> Inheriteable;
 7 
 8         /**
 9          * @param local
10          * @param inheriteable
11          */
12         public TestThread(ThreadLocal<Map<String, Integer>> local,
13                           ThreadLocal<Map<String, Integer>> inheriteable) {
14             super();
15             this.local = local;
16             Inheriteable = inheriteable;
17         }
18 
19         /** 
20          * @see java.lang.Runnable#run()
21          */
22         @Override
23         public void run() {
24 
25             System.out.println("old local" + local.get());
26             System.out.println("old inherit" + Inheriteable.get());
27 
28             Map<String, Integer> map = new HashMap<String, Integer>();
29             map.put("ss", 6);
30             map.put("ss2", 7);
31             map.put("ss3", 8);
32             local.set(map);
33             Inheriteable.set(map);
34 
35             System.out.println("old local" + local.get());
36             System.out.println("old inherit" + Inheriteable.get());
37 
38         }
39 
40     }
41 
42     public static void main(String[] args) {
43 
44         Map<String, Integer> map = new HashMap<String, Integer>();
45         map.put("1", 1);
46         map.put("2", 2);
47         ThreadLocal<Map<String, Integer>> local = new ThreadLocal<Map<String, Integer>>();
48         local.set(map);
49         System.out.println("local:" + local.get());
50 
51         ThreadLocal<Map<String, Integer>> Inheriteable = new InheritableThreadLocal<Map<String, Integer>>();
52         Map<String, Integer> map2 = new HashMap<String, Integer>();
53         map2.put("3", 3);
54         map2.put("4", 4);
55         Inheriteable.set(map2);
56         System.out.println("local:" + Inheriteable.get());
57         TestThread t = new TestThread(local, Inheriteable);
58         Thread th = new Thread(t);
59         th.start();
60 
61         try {
62             th.join();
63         } catch (InterruptedException e) {
64         }
65 
66         System.out.println("local:" + local.get());
67         System.out.println("local:" + Inheriteable.get());
68 
69     }
70 
71 }
代码实例

 

posted @ 2016-04-01 17:44  隔壁的老郭  阅读(182)  评论(0)    收藏  举报