-2

How do I add a delay between 2 functions? I want one function to execute and after some delay another function to execute.

For example in the below code when AI vs CPU is chosen I want the outputs to be delayed....TimeUnit.SECONDS() delays the whole process not each function call ..

So how can I add delay after each function call of CPU and AI in the following code:

 public void actionPerformed(ActionEvent e) {
            option = 3;
            ai.setBackground(Color.WHITE);
            int q = (int) (Math.random() * 2);
            //System.out.println(" I have been called " + q);
            if (q == 1) {
                    System.out.println(" I am inside " + q);
                    text1.setText(" AI  starts ");
                    AI(1);
                    CPU(0);
                    AI(1);
                    CPU(0);
                    AI(1);
                    CPU(0);
                    AI(1);
                    CPU(0);
                } else {
                    //      System.out.println(" I have been inside " + q);
                    text1.setText(" CPU  starts ");
                    CPU(1);
                    AI(0);
                    CPU(1);
                    AI(0);
                    CPU(1);
                    AI(0);
                    CPU(1);
                    AI(0);
                }

        }

    });

EDIT: this is actually a tic tac toe game in which the Computer plays against the AI ....so as the output would be quick ...I want each step to be called and a delay to be there so that each move is visible.

Draken
  • 3,134
  • 13
  • 34
  • 54
lirus
  • 25
  • 7

1 Answers1

0

As it mentioned before Thread.sleep is the way to go. You can create a simple method like this:

public void sleep(long millis){
    try {
        Thread.sleep(millis);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}

An call it whenever you want some delay. If you want delay between each step you have to call it between each step:

CPU(1);
sleep(300);
AI(0);
sleep(300);
/*And so on*/

Important: As Christopher Schneider mentioned if this is a single threaded application your gui will not response while your thread is sleeping.

eldo
  • 1,327
  • 2
  • 16
  • 27