This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes UniqueThreadIdGenerator.getCurrentThreadId() and remains unchanged on subsequent calls.
先看两个例子:
1.
- package com.mytrace.thread;
- public class TestThread {
- public static Integer a = 0;
- /**
- * @param args
- */
- public static void main(String[] args) {
- MyThread my1 = new MyThread();
- MyThread my2 = new MyThread();
- my1.start();
- my2.start();
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(a + "------");
- }
- public static class MyThread extends Thread {
- public void run() {
- // synchronized (a) {
- for (int i = 0; i < 5; i++) {
- a++;
- System.out.println(Thread.currentThread().getName() + ":"
- + a);
- }
- // }
- }
- }
- }
结果:
Thread-0:2
Thread-0:3
Thread-1:2
Thread-1:5
Thread-1:6
Thread-1:7
Thread-1:8
Thread-0:4
Thread-0:9
Thread-0:10
10------
2.
- package com.mytrace.thread;
- public class TestThreadLocal2 {
- private static ThreadLocal<Integer> a = new ThreadLocal<Integer>() {
- public Integer initialValue() { // 初始化,默认是返回 null
- return 0;
- }
- };
- public static void main(String args[]) {
- MyThread my1 = new MyThread();
- MyThread my2 = new MyThread();
- my1.start();
- my2.start();
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(a.get() + "------");
- }
- public static class MyThread extends Thread {
- public void run() {
- for (int i = 0; i < 5; i++) {
- a.set(a.get() + 1);
- System.out.println(Thread.currentThread().getName() + ":"
- + a.get());
- }
- }
- }
- }
结果:
Thread-1:1
Thread-1:2
Thread-1:3
Thread-1:4
Thread-1:5
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
0------
从以上两个例子看出: ThreadLocal为每个线程创建一个ThreadLocal<Integer> a我副本,每个线程各自操作自己的那个副本, 不会影响其它线程的副本..
原文:http://blog.csdn.net/zsxxsz/article/details/6284769