繁体   English   中英

如何使用ThreadLocal.withInitial初始化类型为Map的本地线程?

[英]How to initialise a thread-local with type Map using ThreadLocal.withInitial?

我正在尝试使用“ThreadLocal.withInital”方法初始化Map类型的线程局部

我可以继续设置一个新的ThreadLocal并添加一个setter方法来继续初始化。 但我正试图找到一种方法,是否可以通过初始完成。

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = new ThreadLocal<>();

预期产出:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(<Hash-map that is set with a predefined date and a boolean>)

也许这个:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
        Map<Date, Boolean> map = new HashMap<>();
        map.put(new Date(), true);
        //do other stuff...
        return map;
    });

ThreadLocal.withInitial方法接受一个Functional参数,因此它可以是Lambda,如下所示:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
    Map<Date, Boolean> map = new HashMap<>();
    map.put(new Date(), true);
    return map;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM