线程本地化ThreadLocal

来源:互联网 发布:windows phone官网 编辑:程序博客网 时间:2024/04/29 23:41
  1. class Accessor implements Runnable {  
  2.   private final int id;  
  3.   public Accessor(int idn) { id = idn; }  
  4.   public void run() {  
  5.     while(!Thread.currentThread().isInterrupted()) {  
  6.       ThreadLocalVariableHolder.increment();  
  7.       System.out.println(this);  
  8.       Thread.yield();  
  9.     }  
  10.   }  
  11.   public String toString() {  
  12.     return "#" + id + ": " +  
  13.       ThreadLocalVariableHolder.get();  
  14.   }  
  15. }  
  16.   
  17. public class ThreadLocalVariableHolder {  
  18.   private static ThreadLocal<Integer> value =  
  19.     new ThreadLocal<Integer>() {  
  20.       private Random rand = new Random(47);  
  21.       protected synchronized Integer initialValue() {  
  22.         return rand.nextInt(10000);  
  23.       }  
  24.     };  
  25.   public static void increment() {  
  26.     value.set(value.get() + 1);  
  27.   }  
  28.   public static int get() { return value.get(); }  
  29.   public static void main(String[] args) throws Exception {  
  30.     ExecutorService exec = Executors.newCachedThreadPool();  
  31.     for(int i = 0; i < 5; i++)  
  32.       exec.execute(new Accessor(i));  
  33.     TimeUnit.SECONDS.sleep(3);    
  34.     exec.shutdownNow();          
  35.   }  
  36. }   
  37.   
  38. 我的结果和书上的不一样所以就不再记录 
  39. ThreadLocal对象通常当作静态域存储, 在创建ThreadLocal时,只能通过get() 和set()方法访问对象, get() 返回与对象相关的对象副本,而ser()会将参数插入到为其线程存储的对象,并返回存储原有的对象,increment()和get()方法在ThreadLocalVariableHolder 中演示了这一点,注意到 increment()和get()方法都不是synchronized的,因为ThreadLocal保证不会出现竞争条件


    上面是摘抄TIJ的 线程本地存储 方便以后自己复习使用

0 0
原创粉丝点击