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<>();
public static User getCurrentUser(){
return context.get();
}
public UserContext(User user){
context.set(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)){
new Greeting().hello();
Level.checkLevel();
}
}
}
class Greeting{
void hello(){
User user = UserContext.getCurrentUser();
System.out.println("Hello,"+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 registered user.");
}
}
}
public class Main{
public static void main(String[] args) throws Exception{
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");
}
}
原文地址:https://www.cnblogs.com/csj2018/p/11047825.html
时间: 2024-10-09 09:20:41