匿名内部类中使用类名.this.属性名或类名.this.方法名调用外部类属性或方法

示例:

public class WxMessageInMemoryDuplicateChecker{

  /**
   * 一个消息ID在内存的过期时间:15秒.
   */
  private final Long timeToLive;

  /**
   * 每隔多少周期检查消息ID是否过期:5秒.
   */
  private final Long clearPeriod;
  
  /**
   * 消息id->消息时间戳的map.
   */
  private final ConcurrentHashMap<String, Long> msgId2Timestamp = new ConcurrentHashMap<>();

  /**
   * 后台清理线程是否已经开启.
   */
  private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean(false);

  protected void checkBackgroundProcessStarted() {
    if (this.backgroundProcessStarted.getAndSet(true)) {
      return;
    }
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
          //匿名内部类中使用类名.this.属性名,调用外部类属性
            Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod);
            Long now = System.currentTimeMillis();
            for (Map.Entry<String, Long> entry :
                WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) {
              if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) {
                WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry);
              }
            }
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    t.setDaemon(true);
    t.start();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值