In Java, it is sometimes necessary to suspend a program for a little time, called inertia. Common delay is thread.sleep (int) method, which is very simple. It suspends the current thread for the specified number of milliseconds. Such as
[Java]View PlainCopy
- Try
- {
- Thread.CurrentThread (). Sleep (+); Milliseconds
- }
- catch (Exception e) {}
Here you need to explain the time the thread sleeps. The sleep () method does not allow the program to "strictly" sleep for a specified time. For example, when you use 5000 as a parameter to the sleep () method, the thread may not continue to run until it is actually suspended for 5000.001 milliseconds. Of course, for a typical application, the sleep () method has enough precision for time control.
But if you want to use the exact delay, it's best to use the Timer class:
[C-sharp]View PlainCopy
- Timer timer=new timer (); Instantiating a timer class
- Timer.schedule (new TimerTask () {
- Public void Run () {
- System. out.println ("exit");
- This.cancel ();}},500); //500 ms
This delay is more accurate than sleep. The above delay method runs only once, and if it needs to run multiple times, use timer.schedule(New MyTask (), 1000, 2000); Execute mytask () 2 seconds per interval
Java two delay--thread and timer