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