Q:

How to fix a specific time for a method in java

I am writing a code in Java, that has three main methods which are called in succession. Today, my prof, told me to improve the code by setting a frequency to code which means it that there should be a specific time allocated for each method. If it is done before that time, it should wait for that much time and then call should go to next method.
For example: If the first method has time of 3 seconds, for three seconds it should wait there even if it is done, then move to next method sense.
I am already using a timer in my code to slow down the movement as it is a GUI. I was planning to use another timer, but I feel it will only slow it down. How can I fix the period for that method for a specific time say 3 seconds.
Please let me know if you have any ideas.

A:

If you cannot sleep on your own thread, run the task on another thread. A single executor thread will do nicely, to which you can submit tasks to be executed. Sleeping in the executor thread should not impact the GUI thread.
private Executor executor = Executors.newFixedThreadPool(1);

public void method1() {
    System.out.println("Method 1 called");
}

public void method2() {
    System.out.println("Method 2 called");
}

public void method3() {
    System.out.print("Method 3 called");
}

public void start() {
    executor.execute(new Runnable() {
        private final long WAIT_TIME = 3000; // ms

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            method1();
            sleep(startTime);

            startTime = System.currentTimeMillis();
            method2();
            sleep(startTime);

            startTime = System.currentTimeMillis();
            method3();
            sleep(startTime);
        }

        private void sleep(long startTime) {
            long timeTaken = System.currentTimeMillis() - startTime;
            long timeLeft = WAIT_TIME - timeTaken;
            if(timeLeft < 0) return;

            try {
                Thread.sleep(timeLeft);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    });
}

