首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

JAVA多线程设计形式十一 Thread-Specific Storage Pattern

2012-07-20 
JAVA多线程设计模式十一 Thread-Specific Storage Patternpublic class Log {private static final Thread

JAVA多线程设计模式十一 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();    }}

?

热点排行