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条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程