There is a set() method that sets the value of enum - STARTED . How to make so that after a certain time, the duration the enum value is set as FINISHED . During this period, you can call another doSomething() method and depending on the state of enum (STARTED или FINISHED) different messages are displayed in the console. I think you need to use timer.schedule(timerTask, long delay) , but I don’t know how.
|
1 answer
import java.util.Timer; import java.util.TimerTask; enum SomeEnum { STARTED, FINISHED } public class Example { private volatile SomeEnum someEnum; private static int DURATION = 5000; public void set() { someEnum = SomeEnum.STARTED; new Timer(true).schedule(new TimerTask() { @Override public void run() { someEnum = SomeEnum.FINISHED; } }, DURATION); } public boolean doSomething() { switch (someEnum) { case STARTED: System.out.println("Tick"); return true; case FINISHED: System.out.println("Buy"); return false; default: return false; } } public static void main(String[] args) throws InterruptedException { Example obj = new Example(); obj.set(); while (obj.doSomething()) { Thread.sleep(500); } } } |
timerTaskdo? - Roman C