ThreadLocal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
class ThreadSpecificLog {
private PrintWriter printWriter = null;
ThreadSpecificLog(String filename) {
try {
printWriter = new PrintWriter(new FileWriter(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
void println(String s) {
printWriter.println(s);
}
void close() {
printWriter.println("end of log");
printWriter.close();
}
}
class Log {
private static final ThreadLocal<ThreadSpecificLog> threadSpecificLogCollection = new ThreadLocal<>();
private static ThreadSpecificLog getThreadSpecificLog() {
ThreadSpecificLog threadSpecificLog = threadSpecificLogCollection.get();
if(threadSpecificLog == null) {
threadSpecificLog = new ThreadSpecificLog(Thread.currentThread().getName() + "-log.txt");
threadSpecificLogCollection.set(threadSpecificLog);
}
return threadSpecificLog;
}
static void println(String s) {
getThreadSpecificLog().println(s);
}
static void close() {
getThreadSpecificLog().close();
}
}
class ClientThread extends Thread {
ClientThread(String name) {
super(name);
}
@Override
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");
}
}
public class Test {
public static void main(String[] args) {
new ClientThread("Alice").start();
new ClientThread("Bobby").start();
new ClientThread("Chris").start();
}
}