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

本文详细介绍了Java中的ThreadLocal用法,包括设置和获取线程局部变量的值以及如何避免内存泄露。通过示例展示了单个变量和多个变量的使用,并给出了实际场景如Web项目中保存当前请求用户信息的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文网址:Java多线程--ThreadLocal的用法(有实例)_IT利刃出鞘的博客-CSDN博客

简介

本文用示例来介绍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保存每次请求的用户信息_springboot threadlocal保存用户信息_IT利刃出鞘的博客-CSDN博客

数据库连接

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT利刃出鞘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值