标签:for 示例 current div private i++ bsp 工具 自己
ThreadLocal相当于一个Map<Thread, T>,各线程使用自己的线程对象Thread.currentThread()作为键存取数据,但ThreadLocal实际上是一个包装了这个Map,并且线程只能存取自己的数据,不能操作其它线程的数据。
代码示例:
public static void main(String[] args) { String[] names = new String[]{"A", "B", "C", "D", "E"}; for(int i=0; i<names.length; i++){ final String myName = names[i]; new Thread(){ public void run(){ name.set(myName); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } test(); } }.start(); } /* 运行结果: Thread-0 -> 我的名字叫A Thread-2 -> 我的名字叫C Thread-1 -> 我的名字叫B Thread-3 -> 我的名字叫D Thread-4 -> 我的名字叫E */ } private static ThreadLocal<String> name = new ThreadLocal<String>(); public static void test(){ System.out.println(Thread.currentThread().getName() + " -> 我的名字叫" + name.get()); }
标签:for 示例 current div private i++ bsp 工具 自己
原文地址:http://www.cnblogs.com/hvicen/p/6229832.html