zoukankan      html  css  js  c++  java
  • ThreadLocal在子线程中的访问

    当一个线程T定义一个ThreadLocal局部变量,在线程T下再创建一个子线程T1,那么T1访问不到ThreadLocal

    ThreadLocal使用的是Map,每个线程中有一个Map结构,初始化Map并和此线程绑定

    public class A{
    
    	static int a = 5;
    	
    	public static void main(String[] args) {
    		
    		int b = 7;
    		
    		new Thread(new Runnable() {
    			
    			ThreadLocal<String> thread = new ThreadLocal<String>();
    			
    			@Override
    			public void run() {
    				thread.set("hello");
    				
    				new Thread(new Runnable() {
    					
    					@Override
    					public void run() {
    						System.out.println(String.format("inner thread :)%s", thread.get()));
    						System.out.println(String.format("inner a :)%s", a));
    						System.out.println(String.format("inner b :)%s", b));
    					}
    				}).start();
    				
    				System.out.println(String.format("outer thread :)%s", thread.get()));
    				System.out.println(String.format("outer a :)%s", a));
    				System.out.println(String.format("outer b :)%s", b));
    				
    				while(true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}).start();
    	}
    
    }
    

    输出结果为:

    inner thread :)null
    inner a :)5
    inner b :)7
    outer thread :)hello
    outer a :)5
    outer b :)7
    

    说明子线程访问不到父线程的局部变量ThreadLocal

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    

    每个线程都有与之对应的Map,,每次new一个ThreadLocal,都会在与之对应的Map中添加一条记录

    map.set(this, value);

    其中的key为当前new ThreadLocal()对象本身变量,value为当前ThreadLocal设置的值

    一个线程可以创建多个局部变量,那么Map中就可能存储多条ThreadLocal

  • 相关阅读:
    网站架构(页面静态化,图片服务器分离,负载均衡)方案全解析
    ant例子
    poj 3744 概率dp+矩阵快速幂
    hdu 4284 状态压缩dp
    hdu 4276 树形dp
    hdu 3586 树形dp+二分
    hdu 3001 三进制状压
    hdu 1561 树形dp+分组背包
    hdu 2196 树形dp
    poj 1485 dp
  • 原文地址:https://www.cnblogs.com/zj68/p/14694354.html
Copyright © 2011-2022 走看看