Synchronization and asynchronous of the Java multi-thread ~~~fork/join framework

Source: Internet
Author: User

In the Fork/join framework, there are both synchronous and asynchronous ways of submitting a task. Previously used InvokeAll () method is synchronous, that is, any

This method does not return until all tasks have been processed. And there is another way, which is to use the fork method, which is asynchronous. Also

The fork method returns immediately after you submit the task, and you can continue with the following tasks. This thread will also continue to run.


Here we illustrate the use of async using a program example that queries the disk for a file that ends with a log.


Package Com.bird.concursey.charpet8;import Java.io.file;import Java.util.arraylist;import java.util.List;import Java.util.concurrent.forkjoinpool;import Java.util.concurrent.recursivetask;public class FolderProcessor extends recursivetask<list<string>> {private static final long Serialversionuid = 1l;private String path;private String Extension;public folderprocessor (string path, String extension) {super (); This.path = Path;this.extension = extension;} @Overrideprotected list<string> Compute () {list<string> List = new arraylist<string> (); list<folderprocessor> tasks = new arraylist<folderprocessor> (); File File = new file (path); File content[] = File.listfiles (), if (content! = null) {for (int i = 0; i < content.length; i++) {if (content[i].isdirecto Ry ()) {folderprocessor task = new Folderprocessor (Content[i].getabsolutepath (), extension);//Asynchronously submits the task Task.fork (); Tasks.add (Task);} Else{if (Checkfile (Content[i].getname ())) {List.add (content[i].getabsolutepAth ());}}}} if (Tasks.size () >) {System.out.printf ("%s:%d tasks ran.\n", File.getabsolutepath (), tasks.size ());} Addresultsfromtasks (list,tasks); return list;} /** * That would add to the list of filesthe results returned by the subtasks launched by this task. * @param list * @param tasks */private void Addresultsfromtasks (list<string> list,list<folderprocessor> Tasks) {for (Folderprocessor item:tasks) {List.addall (Item.join ());}}  /** * This method compares if the name of a filepassed as a parameter ends with the extension is looking for * @param Name * @return */private boolean checkfile (String name) {return name.endswith (extension);} public static void Main (string[] args) {Forkjoinpool pool = new Forkjoinpool (); Folderprocessor system = new Folderprocessor ("C:\\Windows", "Log"); Folderprocessor apps = new Folderprocessor ("C:\\Program Files", "Log");p Ool.execute (System);p ool.execute (apps); Pool.shutdown (); list<string> results = Null;results = System.join (); System.out.printf ("System:%d Files found.\n", results.size ()); results = Apps.join (); System.out.printf ("Apps:%d Files found.\n", results.size ());}}

The key of this example are in the Folderprocessor class. Each task processes the content
of a folder. As you know, this content has the following and the kinds of elements:


FF Files


FF Other folders


If the task finds a folder, it creates another task object to process this folder and sends it to
The pool using the fork () method. This method sends the task to the pool that would execute it
If it has a free worker-thread or it can create a new one. The method returns immediately, so
The task can continue processing the content of the folder. For every file, a task compares its
Extension with the one it's looking for and, if they is equal, adds the name of the file to the
List of results.


Once the task has processed all the content of the assigned folder, it waits for the F Inalization
of the tasks it sent to the pool using the join () method. This method called in a task
waits for the finalization of it execution and returns the value returned by the compute ( )
method. The task groups the results of all the tasks it sent with its own results and returns
that list as a return value of th E Compute () method.


The Forkjoinpool class also allows the execution of the tasks in an asynchronous the. You
The used the Execute () method to send the three initial tasks to the pool. In the Main
Class, you also finished the pool using the shutdown () method and wrote information about
The status and the evolution of the tasks running in it. The Forkjoinpool class
Includes more methods that can is useful for this purpose. See the monitoring a Fork/join
Pool recipe to see a complete list of those methods.


Synchronization and asynchronous of the Java multi-thread ~~~fork/join framework

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.