The Java Concurrency API provides abstract phaser of concurrent multi-stage tasks from Java7. If we have concurrent tasks and need to execute them in stages
We can consider phaser this class.
Phaser has a special place where there is no need to deal with Interruptedexception except (awaitadvanceinterruptibly (int phaser) method)
We simulate a scenario:
We have three tasks to find the extensions that were modified in the last 24 hours, from three different folders and their subfolders.
to a. log file. These three tasks consist of the following three steps, respectively:
1. Filter out files with the extension. Log under the specified folder;
2, the first step of the results of filtering, remove the modification time of more than 24 hours of documents;
3. Print the results to the console;
We use phaser to complete the definition of a task.
We have defined two classes:
Filesearcher
Core
Filesearcher is the execution class of the task;
Core is the entrance to the program.
The code is as follows:
Package Com.ali.concurrency.phaser;import Java.io.file;import Java.util.date;import java.util.list;import Java.util.arraylist;import Java.util.concurrent.phaser;import Java.util.concurrent.timeunit;public Class Filesearcher implements Runnable{private final string dir;private final string end;private list<file> results = new Arraylist<file> ();p rivate final Phaser controller;public filesearcher (String dir, String end, Phaser Controller) { This.dir = Dir;this.end = End;this.controller = Controller;} @Overridepublic void Run () {<u>controller.arriveandawaitadvance (); </u>system.out.println ( Thread.CurrentThread (). GetName () + "start ..."); File root = new file (dir), if (Root.isdirectory ()) {dirprocess (dir);} if (!checkresult ()) return;filterfile (); if (!checkresult ()) Return;showinfo ();<u> Controller.arriveandderegister (); </u>system.out.println (Thread.CurrentThread (). GetName () + "work comeleted."); private void Showinfo () {for (File f:results) {System.out.println (Thread. CurrentThread (). GetName () + ":" + F.getabsolutepath ()); <u>controller.arriveandawaitadvance (); </u>}private boolean checkresult () {if (results.size () = = 0) { System.out.println (Thread.CurrentThread (). GetName () + "Phaser" + controller.getphase () + ": 0 results"); System.out.println (Thread.CurrentThread (). GetName () + "Phaser" + controller.getphase () + ": End"); <u>controller . Arriveandderegister (); </u>return false;} Else{system.out.println (Thread.CurrentThread (). GetName () + "Phaser" + controller.getphase () + ":" + results.size () + " Results "); <u>controller.arriveandawaitadvance (); </u>return true;}} private void Dirprocess (String dir) {<u>controller.arriveandawaitadvance (); </u>file dirfile = new File (dir ); file[] Dirfilearr = Dirfile.listfiles (); for (int i = 0; i < dirfilearr.length; i + +) {if (Dirfilearr[i].isfile ()) {Filepro Cess (Dirfilearr[i]);} else if (dirfilearr[i].isdirectory ()) {dirprocess (Dirfilearr[i].getpath ());}}} private void FileproCess (File f) {if (F.getname (). EndsWith (end)) {results.add (f);}} private void Filterfile () {list<file> newresults = new arraylist<file> ();D ate now = new Date (); for (File f:res Ults) {if (f.lastmodified ()-Now.gettime () < TimeUnit.MILLISECONDS.convert (1, timeunit.days)) {newresults.add (f);}} results = Newresults;}}
Package Com.ali.concurrency.phaser;import Java.util.concurrent.phaser;public class Core {public static void main ( String[] args) {Phaser controller = new Phaser (3); Filesearcher system = new Filesearcher ("C:\\testfile\\1", "Log", Controller); Filesearcher apps = new Filesearcher ("c:\\testfile\\2", "Log", Controller); Filesearcher documents = new Filesearcher ("C:\\testfile\\3", "Log", Controller); Thread systemthread = new Thread (System, "system"); Thread Appsthread = new Thread (Apps, "apps"); Thread documentsthread = new Thread (documents, "documents"); Systemthread.start (); Appsthread.start (); Documentsthread.start (); Try{systemthread.join (); Appsthread.join ();d ocumentsthread.join (); catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Terminated:" + controller.isterminated ());}}
Execution Result:
Documentsstart...appsstart ... Systemstart...documents Phaser 2:0 resultsdocuments Phaser 2:end apps Phaser 2:0 resultsapps Phaser 2:end System P Haser 2:4resultssystem Phaser 3:4resultssystem:c:\testfile\1\1_333.logsystem:c:\testfile\1\1_456.logsystem:c:\te Stfile\1\1_666.logsystem:c:\testfile\1\1_777.logsystem work comeleted. Terminated:true
We have logic from the Run method:
The program waits in the first phase to wait for all threads to start;
Then execute dirprocess to filter out the. Log type of file, and then Checkresult
Then filterfile the task of filtering out the empty results.
Then Checkresult
Then Showinfo, where Showinfo waits again after printing
Then the task is written off from the Phaser
The print termination information is true.
There are two states of a phaser:
1. Active state (active), when there are threads participating in synchronization, Phaser is active and synchronized at the end of each phase.
In this state, the execution of Phaser is described earlier.
2, termination State (termination), when all participating threads are unregistered, phaser is in the terminating state. There are no participants in this state of Phaser.
More specifically, when the Onadvance () method returns True, it is in the terminating state. By overriding this method you can change the default behavior. When Phaser is in
When the state is terminated, the synchronous Method Arriveandawaitadvance () method returns immediately and does not perform any synchronous operation.
Please refer to Java7api for other methods.
Execution--phaser of concurrent multi-stage tasks