Controlling the change of concurrent periodic tasks
The Phaser class provides a way to execute each phaser change phase. It is the Onadvance () method. It receives 2 parameters: the current number of stages and the number of registered participants; it returns a Boolean value, False if Phaser continues its execution, otherwise true, that is, phaser ends up running and enters the termination state.
If the registered participant is 0, the default implementation value for this method is true, or false. If you extend the Phaser class and override this method, then you can modify its behavior. Usually, when you are going from one phase to another to perform some action, you will be interested in doing so.
In this guide, you will learn how to control phaser phase changes by implementing a custom version of the Phaser class and overwriting the Onadvance () method to perform some actions that each phase will change. You are going to implement a mock quiz and some students have to complete their exercises. All students must complete the same exercise to continue the next exercise. follow these steps to implement the following example
Package com.packtpub.java7.concurrency.chapter3.recipe6.task;
Import Java.util.Date;
Import Java.util.concurrent.Phaser;
Import Java.util.concurrent.TimeUnit; /** * Implements A subclass of the Phaser class.
Overrides the Onadvance method to * Control the change of phase * * */public class Myphaser extends Phaser {/**
* This is called when the last register thread calls one of the * advance methods in the actual phase * * @param phase * Actual Phase * @param registeredparties * Number of register Ed Threads * @return False to advance the phase, true to finish/@Override protected Boolean onadvance (int phase, int registeredparties)
{switch (phase) {case 0:return studentsarrived ();
Case 1:return finishfirstexercise ();
Case 2:return finishsecondexercise ();
Case 3:return Finishexam ();
Default return true; }/** * This are called in phase 0 to Phase 1 * * @return false to Contin UE with the execution * * Private Boolean studentsarrived () {System.out. printf ("Phaser: The exam are going to start.
The students are ready.\n ");
System.out.printf ("Phaser:we have%d students.\n", getregisteredparties ());
return false; /** * This is called in the Phase 1 to Phase 2 * * @return false to continue wit H The execution * * Private Boolean finishfirstexercise () {System.out. printf ("Phaser:al
L The students has finished the "exercise.\n");
System.out.printf ("Phaser:it ' s turn for the second one.\n");
return false; /** * This is called in the Change form Phase 2 to Phase 3 * * @return false to continue wit
H The execution * * Private Boolean finishsecondexercise () {System.out. printf ("Phaser:all The students has Finis
Hed the second exercise.\n ");
System.out.printf ("Phaser:it ' s turn for the third one.\n");
return false; /** * This is called in the Phase 3 to Phase 4 * * @return true. There are no more phases * * Private Boolean Finishexam () {System.out.printf ("Phaser:all the students Ha
S finished the exam.\n ");
System.out.printf ("Phaser:thank for Your time.\n");
return true;
public static void Main (string[] args) {//creates the Phaser Myphaser Phaser = new Myphaser ();
Creates 5 students and register them in the Phaser Student students[] = new STUDENT[5];
for (int i = 0; i < students.length i++) {students[i] = new Student (phaser);
Phaser.register (); //Create 5 threads for the Students and start them Thread threads[] = new Thread[students.length];
for (int i = 0; i < students.length i++) {threads[i] = new Thread (students[i), "Student" + i);
Threads[i].start (); }//wait for the finalization of the threads for (int i = 0; i < threads.length; i++) {T
ry {threads[i].join ();
catch (Interruptedexception e) {e.printstacktrace (); }//Check that the phaser was in the terminated state System.out.printf ("Main:the Phaser has F
Inished:%s.\n ", phaser.isterminated ()); } class Student implements Runnable {/** * Phaser to control the execution * * Private Phaser PHAs
Er /** * constructor of the class. Initialize its objects * * @param phaser * Phaser to control the execution/public S
Tudent (Phaser Phaser) { This.phaser = Phaser; /** * Main method of the student. It arrives to the exam and does three * exercises. After each exercise, it calls the phaser to the "all *" students finishes the same exercise * * publi c void Run () {System.out.printf ("%s:has arrived to do" exam.
%s\n ", Thread. CurrentThread (). GetName (), New Date ());
Phaser.arriveandawaitadvance (); System.out.printf ("%s:is going.
%s\n ", Thread.CurrentThread (). GetName (), New Date ());
DoExercise1 (); System.out.printf ("%s:has done The" "The" the "the" exercise.
%s\n ", Thread. CurrentThread (). GetName (), New Date ());
Phaser.arriveandawaitadvance (); System.out.printf ("%s:is going to do" second exercise.
%s\n ", Thread.CurrentThread (). GetName (), New Date ());
DoExercise2 (); System.out.printf ("%s:has done" second exercise. %s\n ", THread. CurrentThread (). GetName (), New Date ());
Phaser.arriveandawaitadvance (); System.out.printf ("%s:is going to do" third exercise.
%s\n ", Thread.CurrentThread (). GetName (), New Date ());
DOEXERCISE3 (); System.out.printf ("%s:has finished" exam.
%s\n ", Thread. CurrentThread (). GetName (), New Date ());
Phaser.arriveandawaitadvance ();
/** * Does an exercise be to wait a random time */private void DoExercise1 () {try {
Long Duration = (long) (Math.random () * 10);
TimeUnit.SECONDS.sleep (duration);
catch (Interruptedexception e) {e.printstacktrace ();
}/** * Does an exercise be wait a random time */private void DoExercise2 () {try {
Long Duration = (long) (Math.random () * 10);
TimeUnit.SECONDS.sleep (duration);
catch (Interruptedexception e) { E.printstacktrace ();
}/** * Does an exercise be wait a random time */private void DoExercise3 () {try {
Long Duration = (long) (Math.random () * 10);
TimeUnit.SECONDS.sleep (duration);
catch (Interruptedexception e) {e.printstacktrace ();
}
}
}
Results
Student 0:has arrived to do the exam. Sun June 23:58:44 CST 2016
Student 4:has arrived to do the exam. Sun June 23:58:44 CST 2016
Student 2:has arrived to do the exam. Sun June 23:58:44 CST 2016
Student 1:has arrived to do the exam. Sun June 23:58:44 CST 2016
Student 3:has arrived to do the exam. Sun June 23:58:44 CST 2016
Phaser:the exam are going to start. The students are ready.
Phaser:we have 5 students.
Student 2:is going. Sun June 23:58:44 CST 2016
Student 3:is going. Sun June 23:58:44 CST 2016
Student 4:is going. Sun June 23:58:44 CST 2016
Student 1:is going. Sun June 23:58:44 CST 2016
Student 0:is going. Sun June 23:58:44 CST 2016
Student 3:has Done the exercise Sun June 23:58:44 CST 2016
Student 2:has Done the exercise Sun June 23:58:47 CST 2016
Student 0:has Done the exercise Sun June 23:58:50 CST 2016
Student 4:has Done the exercise Sun June 23:58:51 CST 2016
Student 1:has Done the exercise Sun June 23:58:52 CST 2016
Phaser:all the students has finished.
Phaser:it ' s turn for the second one.
Student 2:is going to do the second exercise. Sun June 23:58:52 CST 2016
Student 1:is going to do the second exercise. Sun June 23:58:52 CST 2016
Student 3:is going to do the second exercise. Sun June 23:58:52 CST 2016
Student 4:is going to do the second exercise. Sun June 23:58:52 CST 2016
Student 0:is going to do the second exercise. Sun June 23:58:52 CST 2016
Student 1:has done the second exercise. Sun June 23:58:56 CST 2016
Student 3:has done the second exercise. Sun June 23:58:59 CST 2016
Student 2:has done the second exercise. Sun June 23:58:59 CST 2016
Student 0:has done the second exercise. Sun June 23:58:59 CST 2016
Student 4:has done the second exercise. Sun June 23:59:00 CST 2016
Phaser:all The students has finished the second exercise.
Phaser:it ' s turn for the third one.
Student 3:is going to do the third exercise. Sun June 23:59:00 CST 2016
Student 4:is going to do the third exercise. Sun June 23:59:00 CST 2016
Student 1:is going to do the third exercise. Sun June 23:59:00 CST 2016
Student 2:is going to do the third exercise. Sun June 23:59:00 CST 2016
Student 0:is going to do the third exercise. Sun June 23:59:00 CST 2016
Student 0:has finished the exam. Sun June 23:59:04 CST 2016
Student 4:has finished the exam. Sun June 23:59:06 CST 2016
Student 1:has finished the exam. Sun June 23:59:07 CST 2016
Student 2:has finished the exam. Sun June 23:59:07 CST 2016
Student 3:has finished the exam. Sun June 23:59:08 CST 2016
Phaser:all The students has finished the exam.
Phaser:thank for the Your time.
Main:the Phaser has finished:true.how it works ...
This exercise simulates a real test with 3 tests. All students must complete the same test to start the next test. In order to implement this must use synchronization, we used the Phaser class, but you implemented your own phaser by extending the original class and overwriting the Onadvance () method.
This method is called by Phaser before the stage changes and all the threads that hibernate in the Wake Arriveandawaitadvance () method. This method receives the current number of stages as an argument, 0 is the first phase, and the number of participants registered. The most useful parameter is actual phase. If you want to perform different actions based on different current phases, you must use the selective structure (if/else or switch) to select the action you want to perform. In the example, we used the switch structure to select different methods for each phase change.
The Onadvance () method returns a Boolean value indicating whether phaser is terminated or not. If you return a value of false indicating that it is not terminated, the thread continues to perform other phases. If the Phaser returns a true value, then Phaser wakes up all the pending threads and transfers phaser to the terminated state, so any subsequent calls to the Phaser method are returned immediately, and the Isterminated () method returns the truth.
In the core class, when you create a Myphaser object, you do not have to represent the number of participants in the Phaser. You have called the Register () method for each Student object to create the registration of the Phaser participant. This call does not establish any relationship between the student object or the thread that executes it and the Phaser. Seriously, the number of participants in the Phaser is a number. There is no relationship between Phaser and the participant.
Turn from: http://ifeve.com/thread-synchronization-utilities-7/