现在的位置: 首页 > 综合 > 正文

Thread-Specific Storage Pattern

2012年05月20日 ⁄ 综合 ⁄ 共 1744字 ⁄ 字号 评论关闭

手工关闭log

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 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 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) {
            }
        }
       
        System.out.println(getName() + " END");
    }
}

 

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();
    
        if (tsLog == null) {
            tsLog = new TSLog(Thread.currentThread().getName() + "-log.txt");
            tsLogCollection.set(tsLog);
            startWatcher(tsLog);
        }

        return tsLog;
    }

    private static void startWatcher(final TSLog tsLog) {
        
        final Thread target = Thread.currentThread();
       
        final Thread watcher = new Thread() {
            public void run() {
                System.out.println("startWatcher for " + target.getName() + " BEGIN");
                try {
                    target.join();
                } catch (InterruptedException e) {
                }
                tsLog.close();
                System.out.println("startWatcher for " + target.getName() + " END");
            }
        };
        watcher.start();
    }
}

抱歉!评论已关闭.