文章目录
Thread-Specific Storage
Thread-Specific Storage 介绍
Thread-Specific Storage模式是即便只有一个入口,也会为内部每个线程分配特有的存储空间的模式;
在Java中,ThreadLocal类实现了该模式;
Thread-Specific Storage 使用场景
- 将原来单线程环境下进行的任务,迁移到多线程环境下进行,又不想对API做过多的修改时,可使用该模式实现平滑过渡;
- 线程持有的信息不会被其他线程所访问;
Thread-Specific Storage 示例代码
//对外提供API的任务代理类
public class Log {
private static final ThreadLocal<TSLog> tsLogCollection=new ThreadLocal<TSLog>();
public static void println(String s){
getTSLog().println(s);
}
public static void close(){
getTSLog().close();
}
private static TSLog getTSLog(){
TSLog tsLog=tsLogCollection.get();
if(tsLog==null){
tsLog=new TSLog(Thread.currentThread().getName()+"-log.txt");
tsLogCollection.set(tsLog);
}
return tsLog;
}
}
//实际执行任务的类
public class TSLog {
private PrintWriter writer=null;
public TSLog(String fileName){
try{
writer=new PrintWriter(new FileWriter(fileName));
}catch(IOException e){
e.printStackTrace();
}
}
public void println(String s){
writer.println(s);
}
public void close(){
writer.println("+++++++++End of Log");
writer.close();
}
}
//请求类
public class ClientThread extends Thread{
public ClientThread(String name){
super(name);
}
public void run(){
System.out.println(getName()+ "BEGIN");
for(int i=0;i<10;i++){
Log.println("I="+i);
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
Log.close();
System.out.println(getName()+" END");
}
}
//入口类
public class Tester {
public static void main(String[] args){
new ClientThread("Alice").start();
new ClientThread("Bobby").start();
new ClientThread("Chris").start();
}
}
Thread-Specific Storage 模式的理解
实际上,Thread-Specific Storage模式通过将所需信息保存在线程本地,避免了在多个线程之间共享数据,从而无需进行显式的互斥操作;之所以说是无需显式的互斥操作是因为,ThreadLocal——资源管理类可能会进行互斥操作;
使用Thread-Specific Storage模式有利于实现从单线程到多线程环境的迁移;
为多线程提供统一的功能入口,同时使用线程特定的信息,避免了调用者传入过多的参数,简化了程序;