threadlocal和static的区别

ThreadLocal类很简单,只有4个方法

void set(Object value);

设置当前线程的线程局部变量的值

public Object get()

该方法返回当前线程所对应的线程局部变量

public void remove()

protected Object initialValue()

这个方法是一个延迟调用方法,在线程第一次调用get()或set(Object)时才执行,并且执行1次。ThreadLocal中默认实现直接返回一个Null

ThreadLocal是为解决多线程程序的并发问题而提出的,可以称之为线程局部变量。与一般的变量的区别在于,生命周期是在线程范围内的。
static变量是的生命周期与类的使用周期相同,即只要类存在,那么static变量也就存在。
那么一个 static 的 ThreadLocal会是什么样的呢?

看下面一个例子,

 
  1. public class SequenceNumber {  
  2.   
  3.  private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){  
  4.   public Integer initialValue(){  
  5.    return 0;  
  6.   }  
  7.  };  
  8.    
  9.  public int getNextNum(){  
  10.   seqNum.set(seqNum.get() + 1);  //执行iniialValue
  11.   return seqNum.get();  
  12.  }  
  13.    
  14.  public static void main(String[] args){  
  15.   SequenceNumber sn = new SequenceNumber();  
  16.   TestClient t1  = new TestClient(sn);  
  17.   TestClient t2  = new TestClient(sn);  
  18.   TestClient t3  = new TestClient(sn);  
  19.     
  20.   t1.start();  
  21.   t2.start();  
  22.   t3.start();  
  23.     
  24.   t1.print();  
  25.   t2.print();  
  26.   t3.print();  
  27.     
  28.     
  29.  }  
  30.    
  31.  private static class TestClient extends Thread{  
  32.   private SequenceNumber sn ;  
  33.   public TestClient(SequenceNumber sn ){  
  34.    this.sn = sn;  
  35.   }  
  36.     
  37.   public void run(){  
  38.    for(int i=0; i< 3; i++){  
  39.     System.out.println( Thread.currentThread().getName()  + " --> " + sn.getNextNum());  
  40.    }  
  41.   }  
  42.     
  43.   public void print(){  
  44.    for(int i=0; i< 3; i++){  
  45.     System.out.println( Thread.currentThread().getName()  + " --> " + sn.getNextNum());  
  46.    }  
  47.   }  
  48.  }  
  49.    
  50. }  

下面是结果

  1. Thread-2 --> 1  
  2. Thread-2 --> 2  
  3. Thread-2 --> 3  
  4. Thread-0 --> 1  
  5. Thread-0 --> 2  
  6. Thread-0 --> 3  
  7. Thread-1 --> 1  
  8. Thread-1 --> 2  
  9. Thread-1 --> 3  
  10. main --> 1  
  11. main --> 2  
  12. main --> 3  
  13. main --> 4  
  14. main --> 5  
  15. main --> 6  
  16. main --> 7  
  17. main --> 8  
  18. main --> 9  

可以发现,static的ThreadLocal变量是一个与线程相关的静态变量,即一个线程内,static变量是被各个实例共同引用的,但是不同线程内,static变量是隔开的

public class JackyDao

{

private static ThreadLocal<Connection> connThreadLocal=new ThreadLocal<Connection>();

pubic static Connection getConnection()

{

if(connThreadLocal.get()==null)

{

Connection conn=ConnectionManager.getConnection();

connThreadLocal.set(conn);

return conn;

}

else


{

return connThreadLocal.get();

}

}

}

原文地址:https://www.cnblogs.com/chenzhao/p/2469703.html