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 ( ) ;
}
}