JAVA 다 중 스 레 드 디자인 모델 11 Thread - Specific Storage 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();
    }
}

좋은 웹페이지 즐겨찾기