-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadLocalTest.java
More file actions
48 lines (36 loc) · 1.18 KB
/
Copy pathThreadLocalTest.java
File metadata and controls
48 lines (36 loc) · 1.18 KB
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
package ThreadTest;
import java.net.ServerSocket;
public class ThreadLocalTest {
ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();
ThreadLocal<String> stringLocal = new ThreadLocal<String>();
public void set() {
longThreadLocal.set(Thread.currentThread().getId());
stringLocal.set(Thread.currentThread().getName());
}
public long getLong() {
return longThreadLocal.get();
}
public String getString() {
return stringLocal.get();
}
public static void main(String[] args) throws InterruptedException {
ThreadLocalTest test = new ThreadLocalTest();
test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
Thread thread1 = new Thread() {
public void run() {
test.set();
//Thread1 线程下
System.out.println(test.getLong());
System.out.println(test.getString());
}
;
};
thread1.start();
thread1.join();
//main线程环境下
System.out.println(test.getLong());
System.out.println(test.getString());
}
}