Java concurrency Programming--runnable callable and future

Source: Internet
Author: User

1.Runnable

Runnable is an interface that is very simple to use: 1. Implement the interface and override the Run Method 2. Create thread 3 with objects of this class. The Run method that automatically calls the object when the thread starts is typically used in conjunction with executorservice in development, decoupling the submission of the task from the execution of the task, and making better use of the various features provided by executor
Executorservice executor = executors.newcachedthreadpool ();                   Executor.submit (new  Runnable () {                         publicvoid  run () {                                  TODO                        }                    }); Executor.shutdown ();
instead of inheriting thread to create threading, using runnable allows your implementation class to implement multiple interfaces at the same time, and the callable and Future,runnable methods do not return task execution results and cannot throw exceptions2.CallableUnlike runnable, callable is a generic parameterized interface that returns the execution results of a thread and throws an exception when it is not properly evaluated.
 Public Interface Callable<v> {    throws  Exception;}
1. Callable does not start the Run method of the implementation class by using the thread's Start method as runnable, so it usually uses the Executorservice submit method to start the call method self-executing task, And Executorservice's submit returns the result of a future type, so callable is often used with the future.
Executorservice pool = executors.newcachedthreadpool ();     future <String> future = Pool.submit (new  callable{           publicvoid Call () {                   //TODO           }    });
Or use the Futuretask package callable again by thread to start (less)
New Futuretask (new  callable{        publicvoid call () {              //  TODO        }  new  Thread (Task); Thread.Start ();
2. Through Executors.callbale (Runnable task,t result) can execute Runnable and return "result", but this result is not Runnable execution result (Runnable the Run method is void type), It is a predefined result of the performer, which can be seen from the principle of its implementation runnableadpter source code
 Public Static<T> callable<t>Callable (Runnable task, T result) {if(Task = =NULL)          Throw NewNullPointerException (); return NewRunnableadapter<t> (task, result);//implemented through Runnableadapter}    Static Final classRunnableadapter<t>ImplementsCallable<t> {     FinalRunnable task; FinalT result; Runnableadapter (Runnable task, T result) { This. Task =task;  This. result =result; }      PublicT Call () {task.run (); returnresult;   //Direct return of incoming results } }
Runnable and callable different points: 1. Runnable does not return task execution results, callable can return to task execution result 2. Callable throws an exception when the task cannot evaluate the result, and runnable cannot be 3. The runnable task can be executed directly by the thread's Start method or by the Executorservice's Submit method.3.FutureThe future saves the results of an asynchronous calculation and can do other work while we perform the task, and provides several methods of * Cancel (Boolean mayinterruptifrunning): An attempt to cancel a task that is executing, and a direct interrupt on the task being performed when the parameter is True Otherwise, returns true if the current task execution completes, or false* iscancel (): Determines whether the task is canceled before the normal execution, and if so, returns true* IsDone (): Determines whether the task is completed * GET (): Wait for the return of the calculation result Throws A * get (long timeout,timeutil unit) If the calculation is canceled: Sets the return time of the calculated result, and throws timeoutexception the benefit of using the future if the calculated result is not returned within the specified time: 1. Gets the result of the task, determines whether the task is completed, and interrupts task 1. The Get method of the future is a good substitute for the Thread.Join or thread,join (long Millis) 2. The Get method of the future can determine whether the execution of the program code (Task) timed out, such as:
Try {      future.get (timeutil.second);} Catch (timeoutexception timeout) {      log4j.log ("Quest off-road, will be canceled!! ");      Future.cancel (); }
4.FutureTaskFuturetask implements the Runnablefuture interface, which provides a constructor that can use runnable to perform tasks, and can use the future to perform tasks and get results. So you can use Futuretask to encapsulate runnable or callable objects, and then submit the task
Futuretask (callable<v> callable)   Futuretask (Runnable Runnable, V result)

5. Application

find the number of files that contain a keyword: Each file launches a thread to find the keyword
 Public classFilesearchtask { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {String path= Args[0]; String keyword= Args[1]; intc = 0; file[] Files=NewFile (path). Listfiles (); ArrayList<Future<Integer>> rs =NewArraylist<>();  for(File file:files) {//each file launches a task to findMatchCount count =NewMatchCount (); Count.file=file; Count.keyword=keyword; Futuretask<Integer> task =NewFuturetask (count); Rs.add (Task); //Add the results returned by the task to the collectionThread thread =NewThread (Task);        Thread.Start (); }         for(future<integer>F:rs) {C+ = F.get ();//iterate to return results and accumulate} System.out.println ("The total number of files that contain keywords is:" +c); }}classMatchCountImplementsCallable<integer>{     Publicfile file;  PublicString keyword; PrivateInteger count = 0;  PublicInteger Call ()throwsException {//the tasks required by the call wrapper thread        if(search (file)) Count++; returncount; }     Public BooleanSearch (file file) {Booleanfounded =false; Try(Scanner Scanner =NewScanner (Newfileinputstream (file))) {             while(!founded &&Scanner.hasnextline ()) {                if(Scanner.nextline (). Contains (keyword)) founded=true; }        } Catch(FileNotFoundException e) {e.printstacktrace (); }        returnfounded; }}

Java concurrency Programming-related examples:Https://github.com/MOBIN-F/Thread

Java concurrency Programming--runnable callable and future

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.