所有分类
  • 所有分类
  • 未分类

Java多线程系列-ThreadLocal的用法(有实例)

简介

本文用示例来介绍Java中ThreadLocal的用法。

方法

方法作用说明
void set(T value)设置值设置线程中本地变量xxx的值
T get()获取值获取线程中本地变量xxx的值
void remove()删除用完ThreadLocal后要调用此方法,不然可能导致内存泄露。

实例

单个变量

package com.example.a;

public class Demo {
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    static void print(String str){
        System.out.println(str + ":" + threadLocal.get());
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal.set("abc");
                print("thread1 variable");

                // 必须要清除,否则可能导致内存泄露
                threadLocal.remove();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal.set("def");
                print("thread2 variable");

                // 必须要清除,否则可能导致内存泄露
                threadLocal.remove();
            }
        });

        thread1.start();
        thread2.start();
    }
}

运行结果

thread1 variable:abc
thread2 variable:def

多个变量

package com.example.a;

public class Demo {
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    private static ThreadLocal<String> threadLocal2 = new ThreadLocal<>();

    static void print(String str){
        System.out.println(str + ":" + threadLocal.get());
        System.out.println(str + ":" + threadLocal2.get());
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal.set("abc");
                threadLocal2.set("abc2");
                print("thread1 variable");

                // 必须要清除,否则可能导致内存泄露
                threadLocal.remove();
                threadLocal2.remove();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal.set("def");
                threadLocal2.set("def2");
                print("thread2 variable");

                // 必须要清除,否则可能导致内存泄露
                threadLocal.remove();
                threadLocal2.remove();
            }
        });

        thread1.start();
        thread2.start();
    }
}

运行结果

thread1 variable:abc
thread1 variable:abc2
thread2 variable:def
thread2 variable:def2

实际场景

Web项目当前请求的用户信息

见:SpringBoot–使用ThreadLocal保存每次请求的用户信息 – 自学精灵

数据库连接

public Connection initialValue() {
    return DriverManager.getConnection(DB_URL);
}

public static Connection getConnection() {  
    return connectionHolder.get();
}

Session管理

public static Session getSession() throws InfrastructureException {  
    Session s = (Session) threadSession.get();
    try {
        if (s == null) {
            s = getSessionFactory().openSession();
            threadSession.set(s);
        }
    } catch (HibernateException ex) {
        throw new InfrastructureException(ex);
    }
    return s;
}
1

评论0

请先

显示验证码
没有账号?注册  忘记密码?

社交账号快速登录