go4it

just do it

模式11--ThreadSpecificStorage

来至《java多线程设计模式》

每个线程有自己的保险箱---ThreadLocal

package Sample2;

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;
    }
}

posted on 2009-05-08 23:56  cxccbv  阅读(304)  评论(0)    收藏  举报

导航