仅为方法的第一次调用调用方法块 [英] Call a block of a method only for the first call of the method

查看:121
本文介绍了仅为方法的第一次调用调用方法块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,在这个方法中我有一个块:

I have a method and inside this method I have a block:

public void method()
{
   [block instructions]
}

但是我的方法调用了两次程序。我希望这个块只执行一次,并且只对第一次出现的方法执行。最好和最优雅的方法是什么?

But this method is called twice in my program. I would like this block to be executed only one time and only for the first occurrence of the method. What would be the best and elegant way to do that?

推荐答案

private static final AtomicBoolean hasRunAtom = new AtomicBoolean();

public void method() {
  if (hasRunAtom.getAndSet(true)) return;
  [block instructions]
}

这篇关于仅为方法的第一次调用调用方法块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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