标签:
内容:ThreadLocal:允许我们创建只能被同一个线程读写的变量,例如Web应用中将变量从前端到后台,并且需要在这次请求的线程中始终可以随时获取到。内部实现是通过一个ThreadLocalMap这个Map结构来实现的,将线程对象作为Key,变量副本作为Value。
public class TestThreadLocal { public static class MyRunnable1 implements Runnable { private ThreadLocal<Integer> threadlocal = new ThreadLocal<Integer>(); @Override public void run() { threadlocal.set(new Random().nextInt(10)); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + " : " + threadlocal.get()); } } public static void main(String[] args) { System.out.println("start"); MyRunnable1 runnable = new MyRunnable1(); Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start(); } }
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/46336539