练习题之ThreadLocal

public class  ThreadLocalMain {
 
  private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
     @Override
     protected Integer initialValue(){
        return 0;
     }
  };
 
 class TestThread implements Runnable {
   private int index;
   public TestThread(int index) {
      this.index = index;
   }
  
  public void run() {
    System.out.println("线程“+index +"的初始Value:" + value.get());
    for(int i=0;i<10;i++) {
        value.set(value.get()+i);
     }
    System.out.println("线程“+index +"的累加Value:" + value.get());
  }
  
  public static void main(String [] args) {
    ThreadLocalMain main = new ThreadLocalMain();
    for(int i=0;i<5;i++) {
      TestThread testThread = main.new TestThread(i);
      new Thread(testThread).start();
    }
  }
 }  
}

关于ThreadLocal的使用请参见:http://ifeve.com/java-theadlocal/

原文地址:https://www.cnblogs.com/moonandstar08/p/5361186.html