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

Posted csj2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了廖雪峰Java11多线程编程-4线程工具类-1ThreadLocal相关的知识,希望对你有一定的参考价值。

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

技术图片

以上是关于廖雪峰Java11多线程编程-4线程工具类-1ThreadLocal的主要内容,如果未能解决你的问题,请参考以下文章

廖雪峰Java11多线程编程-2线程同步-2synchronized方法

廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock

廖雪峰Java13网络编程-1Socket编程-3TCP多线程编程

20200225 Java 多线程-廖雪峰

20200225 Java 多线程-廖雪峰

进程 vs. 线程(python的协程)(转廖雪峰老师python教程)