ThreadLocal类提供了线程局部变量。这些变量在每个线程访问它时都有自己的方法,独立地初始化变量的副本。将变量与当前线程绑定。
package com.frame.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalTest {
//定义一个将会被多个线程操作到的变量
private static int num=0;
//初始化一个ThreadLocal实例,去指向并持有该变量
static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return num;
};
};
//读取该变量时,则是从ThreadLocal实例中去读(每个线程读到的是自己操作的变量副本)
public static int getNum(){
return threadLocal.get();
}
//定义读取变量值的线程
public static class TestThread extends Thread{
public TestThread(){
this.setName("TestThread");
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
System.out.println(this.getName()+"---->"+getNum());
try {
//线程调度均匀些
sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//定义改变变量值的线程(增加)
public static class TestThreadAdd extends Thread{
public TestThreadAdd(){
this.setName("TestThreadAdd");
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
threadLocal.set(getNum()+1);
System.out.println(this.getName()+"---->"+(getNum()));
try {
sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//定义改变变量值的线程(减少)
public static class TestThreadSub extends Thread{
public TestThreadSub(){
this.setName("TestThreadSub");
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
threadLocal.set(getNum()-1);
System.out.println(this.getName()+"---->"+(getNum()));
try {
sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.execute(new TestThread());
executorService.execute(new TestThreadAdd());
executorService.execute(new TestThreadSub());
}
}
输出
最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。
private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return connectionHolder.get();
}