-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
79 lines (66 loc) · 1.43 KB
/
Copy pathMain.java
File metadata and controls
79 lines (66 loc) · 1.43 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
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
77
78
79
package threadLocal;
class User{
String name;
int level;
public User(String name, int level){
this.name = name;
this.level = level;
}
}
class UserContext implements AutoCloseable{
//全局唯一静态变量:
static final ThreadLocal<User> context = new ThreadLocal<>();
//获取当前线程User
public static User getCurrentUser(){
return context.get();
}
//初始化
public UserContext(User user){
context.set(user);
}
//移除ThreadLocal关联的User
public void close(){
context.remove();
}
}
class ProcessThread extends Thread {
User user;
ProcessThread(User user){
this.user = user;
}
public void run(){
try (UserContext ctx = new UserContext(user)){
//step1
Greeting.hello();
//step2
Level.checkLevel();
}
}
}
class Greeting{
static void hello(){
User user = UserContext.getCurrentUser();
System.out.println("Hello, this is thread: "+user.name);
}
}
class Level{
static void checkLevel(){
User user = UserContext.getCurrentUser();
if (user.level > 100){
System.out.println(user.name + " is a VIP user.");
} else {
System.out.println(user.name + " is a registed user.");
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new ProcessThread(new User("bob", 120));
Thread t2 = new ProcessThread(new User("alice", 80));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main end");
}
}