ThreadLocal

Java中的ThreadLocal类允许我们创建只能被同一个线程读写的变量。
因此,如果一段代码含有一个ThreadLocal变量的引用,即使两个线程同时执行这段代码,它们也无法访问到对方的ThreadLocal变量
 
  1. public class Session{  
  2.     private  static ThreadLocal<Session> thread_local=new ThreadLocal<Session>();  
  3.     private Session() {  
  4.     }  
  5.     public static Session getInstance() {  
  6.         if(thread_local.get()==null){  
  7.             thread_local.set(new Session());  
  8.         }  
  9.         return thread_local.get();  
  10.     }  
  11. }  

 

  1. public class Test {  
  2.     public static void main(String[] args) throws NoSuchMethodException,  
  3.             SecurityException, InstantiationException, IllegalAccessException,  
  4.             IllegalArgumentException, InvocationTargetException {  
  5.         final Session session1=Session.getInstance();  
  6.         Session session2=Session.getInstance();  
  7.         System.out.println(session1==session2);  
  8.           
  9.         new Thread(){  
  10.             public void run() {  
  11.                 Session session=Session.getInstance();  
  12.                 System.out.println(session==session1);  
  13.             };  
  14.         }.start();  
  15.     }  

 

true

false 

 

 

原文地址:https://www.cnblogs.com/lnas01/p/5261285.html