Java timer and two delayed -thread

In Java, sometimes you need a little time to pause the program, called the delay. General delay with Thread.sleep (int) method, which is very simple. It suspends the current thread specified number of milliseconds. Such as

[java] view plain copy

  1. try   
  2. {   
  3. Thread.currentThread().sleep(1000);//毫秒   
  4. }   
  5. catch(Exception e){}  

Here we need to explain the thread sleeping time. sleep () method does not allow the program "strict" sleeping specified time. For example, when the parameter 5000 as sleep () method, the thread may continue to run until after the actual suspended 5000.001 milliseconds. Of course, for general applications,, SLEEP () method sufficient accuracy time control.

But if you want to use the exact delay, it is best to use the Timer class:

[c-sharp] view plain copy

  1. Timer timer = new Timer (); // Timer class instantiation   
  2. timer.schedule(new TimerTask(){   
  3. public void run(){   
  4. System.out.println("退出");   
  5. this.cancel ();}}, 500); // five hundred milliseconds  

This delay accurate than sleep. The method of the above-described operation delay only once, run multiple times if desired, using timer.schedule (to MyTask new new (), 1000, 2000); the execution intervals of 2 seconds to MyTask ()

Reprinted from https://blog.csdn.net/zmhinzaghi/article/details/5837735

发布了36 篇原创文章 · 获赞 162 · 访问量 62万+

Guess you like

Origin blog.csdn.net/qq_19004627/article/details/103906896