JAVA多线程设计方式十 Two-Phase Termination Pattern
JAVA多线程设计模式十 Two-Phase Termination Pattern
public class Log { private static final ThreadLocal tsLogCollection = new ThreadLocal(); // 加入一个log public static void println(String s) { getTSLog().println(s); } // 关闭log public static void close() { getTSLog().close(); } // 取得线程特有的log private static TSLog getTSLog() { TSLog tsLog = (TSLog)tsLogCollection.get(); //如果线程是第一次呼叫,就建立新挡案并登陆log if (tsLog == null) { tsLog = new TSLog(Thread.currentThread().getName() + "-log.txt"); tsLogCollection.set(tsLog); } return tsLog; } }
public class TSLog { private PrintWriter writer = null; // 初始化writer字段 public TSLog(String filename) { try { writer = new PrintWriter(new FileWriter(filename)); } catch (IOException e) { e.printStackTrace(); } } // 加入一笔log public void println(String s) { writer.println(s); } // 关闭log 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) { } } Log.close(); System.out.println(getName() + " END"); } }
public class Main { public static void main(String[] args) { new ClientThread("Alice").start(); new ClientThread("Bobby").start(); new ClientThread("Chris").start(); } }