1

I'm doing a console application with Java. I have one method where I need to wait one second, then continue with my method. It's just a simple method, so it means there is no thread involved. What can I do?

My Program looks like this:

  • User writes something
  • Program waits 1 second
  • Then it does calculation.

It has to wait 1 second!

Jay Harris
  • 4,201
  • 17
  • 21
user3549340
  • 121
  • 2
  • 2
  • 7
  • 1
    `there is no thread involved` I'm not a Java expert, but I'm pretty sure every thing runs on a thread – Jay Harris Dec 11 '14 at 21:18
  • 1
    There is a thread. There is the main thread running. You are not using **multiple** threads. See Semih Eker's answer. – Zéychin Dec 11 '14 at 21:18

2 Answers2

7

Try this to pause for 1 second;

try {
    Thread.sleep(1000);                 //1000 milliseconds is one second.
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
  • OP, don't be afraid of the word "Thread" here. This is how you make a simple method wait one second. Just copy-paste. – that other guy Dec 11 '14 at 21:19
  • I tried it with 5000 miliseconds it was like 0.3 seconds long in reality. Is there a reason why it might not work? – user3549340 Dec 11 '14 at 21:23
  • the other guy, please write your answer, I'm ready to learn better way from you.@user3549340 as I specified in question, sleep method take parameter as milliseconds and for one second you must give 1000 milliseconds. – Semih Eker Dec 11 '14 at 21:27
  • @SemihEke, for my own curiosity, in an single threaded application, when might the catch block for InterruptedException be executed? I'm trying to understand why the solution outlined might be superior to, for example, throwing an IllegalStateException. – Robert Bain Dec 11 '14 at 21:35
  • I specified common usage of Thread. As you mentioned, in an single threaded application, InterruptedException isn't required, we can use another Exception types. – Semih Eker Dec 11 '14 at 21:43
2

You can also try this

    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
sol4me
  • 15,233
  • 5
  • 34
  • 34