標籤:
Thread-Specific-Storage[線程保管箱]
一:Thread-Specific Storage的參與者
--->記錄日誌的線程(ClientThread)
--->負責擷取不同線程記錄日誌(Log)
--->負責將日誌寫入檔案的類(TsLog)
二:Thread-Specific Storage模式什麼時候使用
--->當每個線程必須有自己的專屬資訊時,可以將該資訊放入線程保管箱ThreadLocal
三:Thread-Specific Storage思考
--->放置線程特有資訊的地方
(1)線程外--->線程的保管箱ThreadLocal
(2) 線程內-->線程體的局部變數
--->多執行緒共有資料,存在共用互斥
--->共用互斥會降低效能,所以要盡量將共用互斥的範圍縮小
--->線程的效能在於線程代碼的實現
四進階說明
--->
記錄日誌的行為類
1 package com.yeepay.sxf.thread11; 2 3 import java.io.FileWriter; 4 import java.io.PrintWriter; 5 6 /** 7 * 日誌類 8 * @author sxf 9 *10 */11 public class TsLog {12 //寫日誌對象13 private PrintWriter printWriter=null;14 15 //構造器16 public TsLog(String fileName){17 try {18 printWriter=new PrintWriter(new FileWriter(fileName));19 } catch (Exception e) {20 // TODO Auto-generated catch block21 e.printStackTrace();22 }23 }24 25 //添加一條日誌26 public void addLogStr(String logstr){27 printWriter.print(logstr);28 }29 30 //關閉輸出資料流31 public void closeLog(){32 printWriter.close();33 }34 }View Code
代理不同線程的記錄日誌的對象
1 package com.yeepay.sxf.thread11; 2 3 4 /** 5 * 不同線程分發不同的日誌執行個體 6 * @author sxf 7 * 8 */ 9 public class Log {10 //線程的保管箱集合11 private static final ThreadLocal tsLongConteint=new ThreadLocal();12 13 public static void printLogStr(String logStr){14 TsLog log=getTslog();15 log.addLogStr(logStr);16 }17 //擷取當前線程的保管箱18 public static TsLog getTslog(){19 //從線程保管箱中拿去當前線程的TsLog20 TsLog lg=(TsLog) tsLongConteint.get();21 //如果不存在,建立新的TsLog22 if(lg==null){23 lg=new TsLog("/usr/war/"+Thread.currentThread().getName()+"-log.txt");24 tsLongConteint.set(lg);25 }26 return lg;27 }28 //關閉log對象的流29 public static void closeTsLog(){30 getTslog().closeLog();31 }32 }View Code
記錄日誌的線程類
1 package com.yeepay.sxf.thread11; 2 /** 3 * 記錄日誌的線程 4 * @author sxf 5 * 6 */ 7 public class ClientThreaad implements Runnable{ 8 9 public ClientThreaad() {10 11 }12 13 14 @Override15 public void run() {16 for (int i = 0; i <10; i++) {17 Log.printLogStr(Thread.currentThread().getName()+i);18 System.out.println("ClientThreaad.run()==>"+Thread.currentThread().getName()+i);19 }20 Log.closeTsLog();21 }22 23 24 }View Code
測試類別
1 package com.yeepay.sxf.thread11; 2 /** 3 * 測試類別 4 * @author sxf 5 * 6 */ 7 public class Test { 8 9 10 public static void main(String[] args) {11 //開啟三個線程,產生3個檔案,三個線程自己記錄自己的日誌12 new Thread(new ClientThreaad()).start();13 new Thread(new ClientThreaad()).start();14 new Thread(new ClientThreaad()).start();15 }16 17 }View Code
多線程程式設計學習(12)Thread-soecific storage pattern