import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MyThreadLocal2<T> {
private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>());
T initValue()
{
return null;
}
public T getValue()
{
Thread thread = Thread.currentThread();
T t = map.get(thread);
if(t==null&&!map.containsKey(thread))
{
t = initValue();
map.put(thread, t);
}
return t;
}
public void setValue(T t)
{
map.put(Thread.currentThread(), t);
}
}
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SimpleThreadLoger {
private static MyThreadLocal2<Logger> local2 = new MyThreadLocal2<Logger>() {
Logger initValue() {
Logger logger = Logger.getLogger(Thread.currentThread().getName());
try {
logger.addHandler(new FileHandler(Thread.currentThread()
.getName() + ".log"));
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return logger;
};
};
private static Logger getLogger() {
return local2.getValue();
}
public static void setLogger(Logger logger) {
local2.setValue(logger);
}
public static void log(String name) {
getLogger().log(Level.INFO, name);
}
}
public class TestLogger {
public static void main(String[] args) {
for (int i = 0; i < 1000000; i++) {
Thread thread = new LoggerThread();
thread.start();
}
}
static class LoggerThread extends Thread {
int number = 100;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
SimpleThreadLoger.log(getName() + "message");
SimpleThreadLoger.setLogger(null);
}
}
}