Android Multithreading Research (2) Timer

Source: Internet
Author: User

Let's look at a piece of code:

public static void Main (string[] args) {  
    new Timer (). Schedule (new TimerTask () {  
              
        @Override public
        void Run () {  
            System.out.println ("Sunshine Cockroach");  
        }  
    }, 5000);  
          
    int i = 0;  
    while (true) {  
        System.out.println (i++);  
        try {  
            thread.sleep (1000);  
        } catch (Interruptedexception e) {  
            e.printstacktrace ();  
        }  
}}

Modify the above code as follows:

New Timer (). Schedule (new TimerTask () {  
          
    @Override public
    void Run () {  
        System.out.println ("Sunshine Cockroach");  
    }  
}, 2000, 3000);

The timer timer starts executing the Run method after 2000ms and repeats every 3000ms.

If there is a demand, 1s, 2s, 1s, 2s ... Execute the code in the timer separately (even seconds and odd seconds to perform different timers respectively), how do we implement (s on behalf of the second)

Implementation Mode one:

public static void Main (string[] args) {  
    new Timer (). Schedule (new TimerTask () {  
              
        @Override public
        void Run () {  
            System.out.println ("Sunshine cockroach 2 Seconds");  
            New Timer (). Schedule (new TimerTask () {  
                      
                @Override public
                void Run () {  
                    System.out.println ("Sunshine cockroach 4 Seconds")  
                },  
            1000);  
        }}  
    , 1000;  
          
    int i = 0;  
    while (true) {  
        System.out.println (i++);  
        try {  
            thread.sleep (1000);  
        } catch (Interruptedexception e) {  
            e.printstacktrace ();  
        }  
}}

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.