简体   繁体   English

如何确保代码块仅执行ONCE且仅执行ONCE。 永远不会

[英]How do I make sure that a block of code only executes ONCE and only ONCE. And NEVER AGAIN

I've tried creating a public static variable (NOT LOCAL) and purposely making an increment to it and telling Java: 我已经尝试创建一个公共静态变量(NOT LOCAL)并故意对它进行增量并告诉Java:

"If this variable == 0, then execute this code" “如果此变量== 0,则执行此代码”

so that even if that method is called the second time, that block of code won't execute because the variable has changed and is no longer zero... and it will never again be zero because it keeps increasing. 因此,即使第二次调用该方法,该代码块也不会执行,因为变量已经改变并且不再为零......并且它将永远不会再为零,因为它会不断增加。

public void actionPerformed(ActionEvent e){
  if(e.getSource()==deal){/*do something*/}
}

My problem is that the if statment executes more than once when I press the button "deal". 我的问题是当我按下“交易”按钮时,if语句执行了不止一次。

Try something like: 尝试类似的东西:

public class Test {
    private boolean isExecuted;
    public synchronized void executeOnce() { 
        if (isExecuted) {
            return;
        } else {
            //do your stuff
            isExecuted = true;
        }
    }
}

Modify it as per your requirement. 根据您的要求进行修改。 To improve performance, you can use double checked locking. 要提高性能,可以使用双重检查锁定。

Try this way, It's dummy code but through this way, you can execute inner for loop code only once. 尝试这种方式,它是虚拟代码,但通过这种方式,您只能执行一次inner for loop代码。

List<WebElement> allelements = driver.findElements(By.id("id1"));   

int i = 0;

for (WebElement e : allelements) 
{
    i++;

    List<WebElement> secondelements = driver.findElements(By.id("id2"));
    if(i==1)
    {
        for(WebElement ae : secondelements)
        {
                System.out.println(ae.getText());   
        }
    }
    System.out.println(e.getText());
}

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

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