Java Multi-Thread ~~~phaser class implements synchronization of tasks

Source: Internet
Author: User

In multithreaded development, it is often encountered that multiple tasks are assigned to multiple threads, each of which performs his tasks, but each task is divided into several

Stages, each phase expects each thread to be reached simultaneously, meaning that each thread is synchronized, and when a thread finishes the first step, he waits

Wait for the other threads to finish the first step before proceeding to the next, Unison can solve many problems. Here we use an example, this example is to simulate the

File on the calendar machine, find the file ending with log, and his last modification time is within 24 hours, we open 3 threads to complete this

Works and use Phaser to synchronize individual tasks.


Package Com.bird.concursey.charpet5;import Java.io.file;import Java.util.arraylist;import java.util.Date;import Java.util.list;import Java.util.concurrent.phaser;import java.util.concurrent.timeunit;/** * This class implements The operation of searching for files with a determined * extension modified in the last hours in a folder and its SUBFO Lders * * @author Bird September 22, 2014 PM 10:12:18 */public Class FileSearch implements Runnable {//Store the folder in which The search operation would begin.private String initpath;//store the extension of the files we is going to look for.priva Te String end;//Store the full path of the files we'll find with the desired//characteristics.private LIST&LT;STRING&G T Results;private Phaser phaser;public FileSearch (String Initpath, String end, Phaser Phaser) {This.initpath = Initpath;thi S.end = End;this.phaser = Phaser;this.results = new arraylist<string> ();} @Overridepublic void Run () {//the search won ' t begin until all the threads has beenEn created.phaser.arriveAndAwaitAdvance (); System.out.printf ("%s:starting.\n", Thread.CurrentThread (). GetName ()); File File = new file (Initpath), if (File.isdirectory ()) {directoryprocess (file);} if (!checkresults ()) {return;} Filterresults (); if (!checkresults ()) {return;} Showinfo ();p haser.arriveandderegister (); System.out.printf ("%s:work completed.\n", Thread.CurrentThread (). GetName ());} /** * It receives a File object as a parameter and it processes all its files * and subfolders. * * @param file */private void directoryprocess (file file) {file files[] = File.listfiles (); if (Files! = null) {for (int i = 0; i < files.length; i++) {if (Files[i].isdirectory ()) {directoryprocess (files[i]);} else {fileprocess (files[i]);}}} /** * Checks if it extension is equal to the one we be looking for * * @param file */private void fileprocess (file file {if (File.getname (). EndsWith (end)) {Results.add (File.getabsolutepath ());}} /** * Deleting the files that were modified more than the hours ago */private VOID filterresults () {list<string> newresults = new arraylist<string> (); Long actualdate = new Date (). GetTime (  ); for (int i = 0; i < results.size (); i++) {File File = new file (Results.get (i)); Long filedate = File.lastmodified (); if (Actualdate-filedate < TimeUnit.MILLISECONDS.convert (1,timeunit.days)) {Newresults.add (Results.get (i));}} results = Newresults;} Private Boolean checkresults () {if (Results.isempty ()) {System.out.printf ("%s:phase%d:0 results.\n", Thread.CurrentThread (). GetName (), phaser.getphase ()); System.out.printf ("%s:phase%d:end.\n", Thread.CurrentThread (). GetName (), phaser.getphase ());// Stop Phaserphaser.arriveandderegister (); return false;} else{system.out.printf ("%s:phase%d:%d results.\n", Thread.CurrentThread (). GetName (), Phaser.getphase (), Results.size ());//this thread has finished the actual//phase and it wants to being blocked until all the participant threads In the phased//operation finish the actual phase.phaser.arriveAndAwaitAdvance (); return true;}}private void Showinfo () {for (int i = 0; i < results.size (); i++) {File File = new file (Results.get (i)); System.out.printf ("%s:%s\n", Thread.CurrentThread (). GetName (), File.getabsolutepath ());} Phaser.arriveandawaitadvance ();} public static void Main (string[] args) throws Exception {Phaser Phaser = new Phaser (3); FileSearch system = new FileSearch ("C:\\Windows", "Log", phaser); FileSearch apps = new FileSearch ("C:\\Program Files", "Log", phaser); FileSearch documents = new FileSearch ("C:\\programdata", "Log", phaser); Thread systemthread = new Thread (System, "system"); Thread appsthread = new Thread (Apps, "Appsthread"); Thread documentsthread = new Thread (documents, "Documentsthread"); Systemthread.start (); Appsthread.start (); Documentsthread.start (); Systemthread.join (); Appsthread.join ();d ocumentsthread.join (); System.out.println ("Terminated:" + phaser.isterminated ());}}

The program starts creating a Phaser object that'll control the synchronization of the Threads
At the end of each phase. The constructor of Phaser receives the number of participants as
A parameter. Phaser has three participants. This number indicates to Phaser
The number of threads that has to execute an arriveandawaitadvance () method before
Phaser changes the phase and wakes up the threads that were sleeping.
Once Phaser have been created, we launch three threads that execute three different
FileSearch objects.


the first instruction in the run () method of this FileSearch object was a call to the
AR Riveandawaitadvance () method of the Phaser object. As we mentioned earlier, the
Phaser knows the number of threads, the We want to synchronize. When a thread calls this
method, Phaser decreases the number of threads that has to finalize the actual phase and
P UTS this thread to sleep until all the remaining threads finish this phase. Calling this method
at the beginning of the run () method makes none of the FileSearch threads begin their
job until All the threads has been created.


at the end of phase one and phase, we check if the phase have generated results and The
list with the results have elements, or otherwise the phase hasn ' t generated results and the list
is empty. In the first case, the Checkresults () method calls Arriveandawaitadvance ()
as explained earlier. In the second case, if the list is empty, there's no point in the thread
continuing with its execution, so it returns. But notify the phaser that there would be is
one less participant. For this, we used Arriveandderegister (). This notifies the phaser
that this thread have finished the actual phase, but it won ' t participate on the future phases, So
the Phaser won ' t has to wait for it to continue.


At the end of the phase three implemented in the Showinfo () method, there are a call to the
Arriveandawaitadvance () method of the Phaser. With this call, we guarantee the
Threads finish at the same time. When this method ends it execution, there is a call to the
Arriveandderegister () method of the Phaser. With this call, we deregister the threads
Of the phaser as we explained before, so if all the threads finish, the phaser would have zero
Participants.


Finally, the main () method waits for the completion of the three threads and calls the
Isterminated () method of the Phaser. When a phaser has zero participants, it enters the
So called termination the state and the This method returns True. As we deregister all the threads of
The phaser, it would be in the termination state and this call would print true to the console.

Java multi-thread ~~~phaser class implements synchronization of tasks

Related Article

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.