Is it possible to make the program wait in java? im running a while loop and i want to make the program wait for 1 second before going through the loop again. How can i do that?
Use the Thread.sleep method. However, this sounds like the typical busy/wait antipattern. Is the Object wait/notify more appropriate for your needs insteading of polling for some state change?
This is what im trying to do. I have a int with a value of 5. I have another int with a value of 1. Im adding 1 + 5 = 6 and getting all the number between 1 and 6 which are 2,3,4 and 5. Im doing this using a while loop. Now i get the number but unfortunately the proccess is over and done with in less than a second. I want it to wait before it goes through the loop again. Im not suere weather to use sleep or wait or what. What would u sujjest?
You should use sleep(), but notice that the argument to that method is the time to sleep in milliseconds. In order to sleep for a second, you need to call sleep(1000).
Admit nothing. Blame everyone. Be bitter.
MR Chahal
Greenhorn
Joined: Nov 27, 2005
Posts: 14
posted
0
Hello
when i use the sleep function, the program sleep but not exactly like i want it to. When i get the numbers from between 1 and 6, i am just putting them in a textbox. Before the sleep funciton, the whole loop was completed in less than a second. After i used the sleep function, the system wait and then all the numbers appear in the text box.
How can i make it so that it put 2 in the text box, sleeps for 500 miliseconds, then goes through the loop and puts 3 in the textbox, again wait for 500 millisec, go through loop again and put 4 in the textbox like it would be if i used a timer.
No it is not working. This is what my code looks like: ---------------------------- while (int1 != int2) { tp1c = int1 +1; //textbox1.setText(""int1); // this is for testing. try { Thread.sleep( 500); } catch( InterruptedException e ) { }
} -----------------------------
What happens is that it just waits for 500 milliseconds and then executes the code so all i see in textbox1 is 5 instead of 2 then wait for 500 millisecond , then 3, wait for 500 milliseconds, then 4, wait for 500 milliseconds and then finally 5.
what am i doing wrong? [ April 17, 2006: Message edited by: MR Chahal ]