简体   繁体   中英

Execute an instruction every x seconds in a for loop of an arraylist using JAVA

I think this question has already been answered but I can't find the right solution to my problem.

I have a arraylist containing several "ball" objects. I want to browse this list to "shoot" each ball with x seconds between them. Here is the code I have, I tried with the Timertask , System.currentMillis() / nano but I can't find a solution that works.

for(Ball ball: ballList) { // Browse the list
   ball.setMove(true);     // Launch ball

   // Wait x seconds before sending new one
   // ...
}

Does anyone have a solution?

You can use Thread.sleep() or TimeUnit.SECONDS.sleep() which is a wrapper on Thread.sleep() for better readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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