Java two delay--thread and timer

Source: Internet
Author: User

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
    1. Try
    2. {
    3. Thread.CurrentThread (). Sleep (+); Milliseconds
    4. }
    5. 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
    1. Timer timer=new timer (); Instantiating a timer class
    2. Timer.schedule (new TimerTask () {
    3. Public void Run () {
    4. System.   out.println ("exit");
    5. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.