廖雪峰Java11多线程编程-4线程工具类-1ThreadLocal

2020-12-13 02:40

阅读:522

标签:gis   ring   except   eve   turn   void   user   RoCE   rem   

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 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");
    }
}

技术图片

廖雪峰Java11多线程编程-4线程工具类-1ThreadLocal

标签:gis   ring   except   eve   turn   void   user   RoCE   rem   

原文地址:https://www.cnblogs.com/csj2018/p/11047825.html


评论


亲,登录后才可以留言!