ThreadLocal使用線程私有方式解決變量共享問題,主要運用在全局設置.java
簡單事例代碼(來自java特種兵)ide
package com.ydy.thread.treadlocal; /** * * @author ydy * */ public class TreadLocalTest { static class ResourceClass{ public final static ThreadLocal<String> RESOURCE_1=new ThreadLocal<>(); public final static ThreadLocal<String> RESOURCE_2=new ThreadLocal<>(); } static class A{ public void setOne(String value) { ResourceClass.RESOURCE_1.set(value); } public void setTwo(String value) { ResourceClass.RESOURCE_2.set(value); } } static class B{ public void display() { System.out.println(ResourceClass.RESOURCE_1.get()+":"+ResourceClass.RESOURCE_2.get()); } } public static void main(String[] args) { final A a=new A(); final B b=new B(); for(int i=0;i<15;i++) { final String resource1="線程-"+i; final String resource2=i+""; new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { a.setOne(resource1); a.setTwo(resource2); b.display(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { ResourceClass.RESOURCE_1.remove(); ResourceClass.RESOURCE_2.remove(); } } }).start(); } } }
實現原理this
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }