"Java Concurrency" timer technology in traditional threading technology

Source: Internet
Author: User

Traditional threading Technology has a timer, the class of the timer is a timer, we use the purpose of the timer is to give it a task, let it complete the task at a specified time. So let's take a look at the methods in the Timer class (mostly the usual TimerTask() methods):

return value method name method description
void Schedule (timertask task, lo ng delay)
void Schedule (timertask task, long delay, lo ng period) schedules the specified task to start a recurring fixed deferred execution from the specified delay.
void Schedule (timertask task, Date time)
void Schedule (timertask task, Date Firsttime, long period) Schedules the specified task to begin repeating fixed deferred execution at a specified time.

The first two are executed after a specified delay, and two are executed at a specified time or repeatedly. We used to look at the use of timers for two examples.
Write a simple demo using the timer and then slowly extend it.

 Public  class traditionaltimer {     Public Static void Main(string[] args) {//Demo for simple timer        NewTimer (). Schedule (NewTimerTask () {@Override             Public void Run() {//actually throws an object in and we can manipulate all the methods of this object here.System.out.println ("--boom--");//Explosion}        }, -, the);//print seconds, output once a second for easy observation         while(true) {System.out.println (NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

We use an anonymous inner class to define a TimerTask object, need to rewrite the run () method, and then run the program, you can see the first time 2 seconds after the printing "–boom–, after every 3 seconds after printing."
We can also implement the above repetition, we use the timer "serial set"! That is, the timer in the next set of timers, a timer task is finished, at the end of the task to install a timer. Then we need to define our own timer task, put a timer in our timer task, and throw the custom timer task into it. Then we turn on the timer and throw our own timer task into it. As follows:

 Public  class traditionaltimer {     Public Static void Main(string[] args) {//Customize a Timer taskClass Mytimertask extends TimerTask {@Override             Public void Run() {System.out.println ("--boom--");//When the task is finished, reload a timer and throw in the custom timer task                NewTimer (). Schedule (NewMytimertask (), the); }        }NewTimer (). Schedule (NewMytimertask (), -);//Outside open timer         while(true) {//print seconds, output once a secondSystem.out.println (NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

In this way, we have easily implemented a serial explosion through the "chain" of timers. But now the problem comes, the method provided above is repeated every fixed time, if I want to execute every 2 seconds, and then execute once every 4 seconds, and then execute once every 2 seconds, and then every 4 seconds to execute once ... How can this be achieved?
In this way, we define a global private member variable to record the number of explosions, an odd number of times 2 seconds to explode, even a few times 4 seconds to explode, or vice versa, modified as follows:

 Public  class traditionaltimer {    Private Static intCount =0;//Record the number of explosions     Public Static void Main(string[] args) {Class Mytimertask extends TimerTask {@Override             Public void Run() {count = (count +1) %2;//Results only 0 and 1System.out.println ("--boom--");NewTimer (). Schedule (NewMytimertask (), -+ -*count);//Set a new timing time based on the count result}        }NewTimer (). Schedule (NewMytimertask (), -); while(true) {//print seconds, output once a secondSystem.out.println (NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

In that case, we've implemented a custom explosion interval. The above is done by defining a global private variable, but we can also do this: not to achieve two different time intervals of the serial bombing? I can define two timer tasks A and B, in a after the start timer, the B task loaded in, b after the start timer put a loaded in, so also can. As follows:

 Public  class traditionaltimer {     Public Static void Main(string[] args) {NewTimer (). Schedule (NewMytimertaska (), -);//a and B casually open a         while(true) {//print seconds, output once a secondSystem.out.println (NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}//Custom two Timer task class, inherit TimerTask canClass Mytimertaska extends TimerTask {@Override     Public void Run() {System.out.println ("--booma--");NewTimer (). Schedule (NewMYTIMERTASKB (),4000); }}class Mytimertaskb extends TimerTask {@Override     Public void Run() {System.out.println ("--boomb--");NewTimer (). Schedule (NewMytimertaska (), -); }   }

This allows for a custom time interval for the serial bombing. The traditional timer technology is summed up so much bar ~

-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15

"Java Concurrency" timer technology in traditional threading technology

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.