99网
您的当前位置:首页《图解java多线程设计模式》中的 ThreadSpecificStrorage 模式

《图解java多线程设计模式》中的 ThreadSpecificStrorage 模式

来源:99网

ClientThread:表示调用log的线程的类

public class ClientThread extends Thread {
    public ClientThread(String name){
        super(name);
    }

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

Log:创建日志的类

public class Log {
    private static final ThreadLocal<TSLong> telecommunication = new ThreadLocal<>();

    //写日志
    public static void println(String s){
        getTSLong().println(s);
    }

    public static void close(){
        getTSLong().close();
    }

    private static TSLong getTSLong(){
        TSLong tsLong = telecommunication.get();
        if (tsLong == null){
            tsLong = new TSLong(Thread.currentThread().getName()  + "-log.txt");
            telecommunication.set(tsLong);
        }
        return tsLong;
    }
}

Main: 可以应用于将单线程程序该表为多线程程序

public class Main {
    public static void main(String[] args) {
        new ClientThread("alice").start();
        new ClientThread("bobby").start();
        new ClientThread("chira").start();
    }
}

TSLong: 创建日志的类

public class TSLong {
    private PrintWriter writer = null;
    public TSLong(String filename){
        try {
            writer = new PrintWriter(new FileWriter(filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //写日志
    public void println(String a){
        writer.println(a);
    }

    //关闭日志
    public void close(){
        writer.println("========end of log========");
        writer.close();
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容