多线程编程模式之Thread-Specific Storage模式
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                多线程编程模式之Thread-Specific Storage模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                文章目錄
- Thread-Specific Storage
 - Thread-Specific Storage 介紹
 - Thread-Specific Storage 使用場景
 - Thread-Specific Storage 示例代碼
 - Thread-Specific Storage 模式的理解
 
Thread-Specific Storage
Thread-Specific Storage 介紹
Thread-Specific Storage模式是即便只有一個入口,也會為內部每個線程分配特有的存儲空間的模式;
在Java中,ThreadLocal類實現了該模式;
Thread-Specific Storage 使用場景
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模式有利于實現從單線程到多線程環境的遷移;
為多線程提供統一的功能入口,同時使用線程特定的信息,避免了調用者傳入過多的參數,簡化了程序;
總結
以上是生活随笔為你收集整理的多线程编程模式之Thread-Specific Storage模式的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: OceanBase-概述
 - 下一篇: 云计算与虚拟化的关系是什么?