wait - How to delay in Java? -
this question has answer here:
i trying in java , need wait / delay amount of seconds in while loop.
while (true) { if (i == 3) { = 0; } ceva[i].setselected(true); //need wait here ceva[i].setselected(false); //need wait here i++; }
i want build step sequencer , i'm new java. suggestions ? thanks!
if want pause use java.util.concurrent.timeunit
:
timeunit.seconds.sleep(1);
to sleep 1 second or
timeunit.minutes.sleep(1);
to sleep minute.
as loop, presents inherent problem - drift. every time run code , sleep drifting little bit running, say, every second. if issue don't use sleep
.
further, sleep
isn't flexible when comes control.
for running task every second or @ 1 second delay strongly recommend scheduledexecutorservice
, either scheduleatfixedrate
or schedulewithfixeddelay
.
for example, run method mytask
every second (java 8):
public static void main(string[] args) { final scheduledexecutorservice executorservice = executors.newsinglethreadscheduledexecutor(); executorservice.scheduleatfixedrate(app::mytask, 0, 1, timeunit.seconds); } private static void mytask() { system.out.println("running"); }
and in java 7:
public static void main(string[] args) { final scheduledexecutorservice executorservice = executors.newsinglethreadscheduledexecutor(); executorservice.scheduleatfixedrate(new runnable() { @override public void run() { mytask(); } }, 0, 1, timeunit.seconds); } private static void mytask() { system.out.println("running"); }
Comments
Post a Comment