gaokang 2016-04-10 12:53 采纳率: 42.9%
浏览 2338
已采纳

关于java的匿名内部类和泛型

public class Counter {

private static ThreadLocal<Integer> counterContext = new ThreadLocal<Integer>(){
    protected synchronized Integer initialValue(){
        return 10;
    }
};

}

请教下上面这个类当中的这个匿名内部类起了什么作用,这个return 的10是传给了谁了呢?另外关于ThreadLocal中的这个泛型的用法不是很理解,我对泛型的理解仅仅是 ArrayList这类集合的泛型,说明里面只能存放String,对于ThreadLocal这种类的泛型又是什么意思呢?是ThreadLocal里面的某一个成员变量只能是Integer吗?

  • 写回答

3条回答 默认 最新

  • 毕小宝 博客专家认证 2016-04-10 13:05
    关注

    首先,这端代码本质上是定义了一个ThreadLocal变量,等价于:

     private static ThreadLocal<Integer> counterContext = new ThreadLocal<Integer>()
    

    这样的话它使用的就是ThreadLocal的默认的initialValue方法指定的值。
    其次,你这里的代码相等于实例化了一个ThreadLocal类型的匿名类,并重写了它的initialValue方法,这里的return 10并没有传给谁,而是整个方法声明需要返回一个初始化值。这个方法会在某个线程第一次调用get操作时返回。API的说明是这样的:

     Returns the current thread's "initial value" for this
         * thread-local variable.  This method will be invoked the first
         * time a thread accesses the variable with the {@link #get}
         * method,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题