On Java concurrent programming

Source: Internet
Author: User

 Packagetest;ImportJava.io.File;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.Reader;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.TimeUnit; Public classTest { Public Static voidGetjavafile (String currentpath,list<file>files) {File dir=NewFile (Currentpath); if(Dir.exists ()) {File temp[]=Dir.listfiles (); if(Temp! =NULL)            {                             for(File b:temp) {if(B.isfile () && b.tostring (). EndsWith (". Java") {files.add (b); }                    Else if(B.isdirectory ()) {Getjavafile (b.tostring (), files); }                }            }        }    }     Public Final Static floatPercent = (float) 0.9;  Public Final Static intPoolsize = (int) (Runtime.getruntime (). Availableprocessors ()/(1-percent));  Public Static voidMain (string[] args)throwsexception{//TODO auto-generated Method Stub//initializing a collection of filesString Path = "G:" +file.separator+ "src"; List<File> fs =NewArraylist<>();                Getjavafile (path, FS); //Sequential Execution        LongStart =System.currenttimemillis (); intTotal = 0;  for(File s:fs) {inti =GetCount (s); //System.out.println (S.getname () + "Length:" +i);total+=i; }        LongEnd =System.currenttimemillis (); System.out.println ("Sequential Execution Time:" + (End-start) + "Results obtained:" +Total ); FinalExecutorservice Executorpool =Executors.newfixedthreadpool (poolsize); Finallist<callable<integer>> partitions =NewArraylist<>();  for(FinalFile F1:fs) {Partitions.add (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {//TODO auto-generated Method StubInteger i =GetCount (F1); //System.out.println (F1.getname () + "Length:" +i);                    returni;        }            }); }        LongSTARTBINGFA =System.currenttimemillis (); FinalList<future<integer>> nums = Executorpool.invokeall (partitions,5, timeunit.minutes); intTOTALBINGFA = 0;  for(FinalFuture<integer>i:nums) {TOTALBINGFA= totalbingfa+I.get ();        } executorpool.shutdown (); LongENDBINGFA =System.currenttimemillis (); System.out.println ("Concurrent Time:" + (ENDBINGFA-STARTBINGFA) + "Results obtained:" +TOTALBINGFA); }         Public Static intGetCount (File f)throwsioexception{intCount = 0; Reader BR=NewFileReader (f); //String line = "";        intC;  while((c = Br.read ())! = 1) {            if(' a ' = = (Char) c) {count++; }        }        returncount; }}

As you can see, I set up a large number of files and then execute them using concurrency and sequence, and the results are as follows:

Sequential execution time: 140 results found: 14002
Concurrent time: 86 results found: 14002
As you can see, the improvement is not particularly obvious because the IO-intensive features of the task in the code are not obvious, but in this case, the time is still improved, using the thread pool approach, first defining a task set partitions,

Final New Arraylist<> ();

Where integer represents the return type of the task

Then define tasks for the task set, such as a read file and return an integer type of data.

Then define the task service

Final Executorservice Executorpool =executors.newfixedthreadpool (poolsize);

This sets the size of the thread pool, which is the number of tasks that can be run concurrently.

And then start executing

Final list<future<integer>> nums = Executorpool.invokeall (partitions,5,timeunit.minutes);

This returns the result of the return of the entire set of tasks, and then we traverse the nums and use the Get method to get a single result.

Finally, you close the thread pool.

Executorpool.shutdown ();

The size of the thread pool is not the bigger the better, depending on the environment,

On Java concurrent programming

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.