Java custom Timer

Source: Internet
Author: User

In Java, the timer function does not have the pause and continue timing function. Therefore, if you want to implement these two functions, you can write a timer by yourself. Below is a Timer class that I write myself.

The Code is as follows:

// Timer public class keeptime {private long s = 0; private Boolean tm_flag; private mytask MT; Public keeptime () {}// start timing public void start_time () {If (MT = NULL) {Mt = new mytask (); tm_flag = true; Mt. start () ;}// stop the public void stop_time () {This. tm_flag = false; this. mt = NULL;} private class mytask extends thread {@ overridepublic void run () {While (tm_flag) {// system. out. println (S + ""); s ++; try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}}// get time public long gettime () {return s ;}// reset time public void resettime () {This. S = 0 ;}public Boolean gettmfalg () {return tm_flag ;}}

Start and continue to call start_time, stop and pause call stop_time,

Some people may ask why th_flag is not directly controlled by setting th_flag. I used to set th_flag to false and the thread will not be available,

So we need to re-open a thread, which is often used in games.

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.