Threadlocal能够为每个线程分配一份单独的副本,使的线程与线程之间能够独立的访问各自副本。Threadlocal 内部维护一个Map,key为线程的名字,value为对应操作的副本。
/**
* Created by majun on 16/3/23.
*/
public class ThreadLocalTest {
/*
Threadlocal为每个线程维护一个单独的副本, 线程之间互不影响
*/
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
//获取下一个序列值
public int getNextNum() {
threadLocal.set(threadLocal.get() + 1);
return threadLocal.get();
}
/*
*/
public static void main(String[] args) {
ThreadLocalTest threadLocalTest = new ThreadLocalTest();
Client client1 = new Client(threadLocalTest);
Client client2 = new Client(threadLocalTest);
Client client3 = new Client(threadLocalTest);
Thread thread1 = new Thread(client1);
Thread thread2 = new Thread(client2);
Thread thread3 = new Thread(client3);
thread1.start();
thread2.start();
thread3.start();
}
static class Client implements Runnable {
private ThreadLocalTest threadLocalTest;
public Client(ThreadLocalTest threadLocalTest) {
this.threadLocalTest = threadLocalTest;
}
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("thread[" + Thread.currentThread().getName() + "] --> nextNumber=[" +
threadLocalTest.getNextNum() + "]");
}
}
}
}