什么时候和如何使用ThreadLocal变量? [英] When and how should I use a ThreadLocal variable?

查看:377
本文介绍了什么时候和如何使用ThreadLocal变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该何时使用 ThreadLocal 变量?

如何使用?

推荐答案

一个可能的(常见的)使用是当你有一些对象不是线程安全的,但你想避免同步对象的访问(我在看你, SimpleDateFormat )。

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object.

例如:

public class Foo
{
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyyMMdd HHmm");
        }
    };

    public String formatIt(Date date)
    {
        return formatter.get().format(date);
    }
}

文档

这篇关于什么时候和如何使用ThreadLocal变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆