public class TSLog {
private PrintWriter writer = null;
public TSLog(String filename){
try {
writer = new PrintWriter(new FileWriter(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
public void println(String s){
writer.println(s);
}
public void close(){
writer.println("=== END OF LOG ===");
writer.close();
}
}
public class Log {
private static final ThreadLocal tsLogCollection = new ThreadLocal();
public static void println(String s){
getTSLog().println(s);
}
public static void close(){
getTSLog().close();
}
private static TSLog getTSLog(){
TSLog tsLog = (TSLog) tsLogCollection.get();
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) {
e.printStackTrace();
}
}
Log.close();
System.out.println(getName() + " END");
}
}