Java Multithreaded Implementation Timer task

Source: Internet
Author: User

Volatile is a weak synchronization mechanism keyword, which can only realize the visible function in the synchronization mechanism, and cannot implement mutually exclusive access. When used on a variable's declaration, it means that when multiple threads get this variable, the data is up-to-date (the variable automatically updates the latest data).

Custom Scheduled Tasks
Task Management Classes
 PackageCom.effectJava.Chapter3;ImportJava.util.concurrent.TimeUnit; Public classManagertask {Private  Static  BooleanIsmanagertaskend;  Public synchronized  Static voidSetismanagertaskend (Booleanflage) {Ismanagertaskend=Flage; }     Public synchronized Static BooleanIsismanagertaskend () {returnIsmanagertaskend; }//private static Mytimetask Timetask = new Mytimetask ();     Public Static voidMain (String ... args)throwsException {//To open a task thread        NewThread () {@Override Public voidrun () { while(true){                    if(Isismanagertaskend ()) {//The task thread is not turned onSetismanagertaskend (false); NewMytimetask (). Start ();        }}}}.start (); //Open Timetask TaskSetismanagertaskend (true); TimeUnit.SECONDS.sleep (1); //Close//Setismanagertaskend (FALSE); //Close TimetaskMytimetask.setflagestrue (true); TimeUnit.SECONDS.sleep (2); Mytimetask.setflagestrue (false); Setismanagertaskend (true); }}

Task Processing Class

 PackageCom.effectJava.Chapter3; Public classMytimetaskextendsthread{Private  volatile  Static Booleanflages; Private  Static  intcount; //Setting Visibility     Public Static   Booleanisflages () {returnflages; }     Public  Static   voidSetflagestrue (Booleanflage) {Flages=Flage; } @Override Public voidrun () { while(!isflages ()) {System.out.println ("Perform Tasks"); //Execute the Task code        }    }     Public  synchronized Static  intrecount () {returncount++; }     Public  synchronized Static  intGetCount () {returncount; }}

Java Multithreaded Implementation Timer task

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.