Java multithreading callable and future classes

Source: Internet
Author: User
Tags thread class

Public interface callable<v> A task that returns results and may throw an exception. The implementing person defines a method called call without any parameters .

public interface future<v> The future represents the result of an asynchronous calculation. You can only use the get method to get the results after the calculation is complete

1. Thread Processing returns results

In general development, using multi-threading, the most common is: 1. Implement the Runnable interface; 2. Inherit the thread class.

But the Run method is not returning results and it is difficult to meet our needs. At this point, the common approach is to implement the callable interface

The callable interface provides a call method entry that we can execute by implementing the Call method, which supports generics and can be used to obtain the desired result type through generic parameters.

 2. Close the thread pool

The thread pool can be closed by invoking the shutdown or Shutdownow method of the thread pool, but they are implemented differently.

The shutdown principle simply sets the state of the thread pool to shutdown state, and then interrupts the thread that does not begin the task.

The principle of shutdownnow is to traverse the worker threads in the thread pool and then call the thread's interrupt method one at a time, so be aware that if there is a task that cannot respond to the interruption, it may never be terminated. Shutdownnow first sets the status of the thread pool to stop, and then tries to stop all threads that are executing or pausing the task, and returns a list of tasks waiting to be executed

 package   com.yyx.test;  import   java.util.concurrent.Callable;  public  class  mycallable implements  callable<string> {
    private   String name;  public   mycallable (String name) { this . Name = name; } @Override  public  String call () throws Exception { return  name + "content returned by task" 
     
      ; }}
     
 Packagecom.yyx.test;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classCallablefuturetest { Public Static voidMain (string[] args) {Try {            //Create a pool of threadsExecutorservice pool=Executors.newcachedthreadpool (); //Create multiple tasks with return valuesList<future> listfuture=NewArraylist<future>();  for(inti=1;i<=5;i++) {callable C=NewMycallable ("+i +" Threads "); //perform tasks and get future objectsFuture F =Pool.submit (c); //determine if the future object has been completed                if(F.isdone ()) {listfuture.add (f); }                            }                        //Close the thread poolPool.shutdown (); //get run results for all concurrent tasks             for(Future future:listfuture) {//gets the return value of the task from the future object and outputs it to the consoleSystem.out.println (">>>" +future.get (). toString ()); }        } Catch(Exception e) {e.printstacktrace (); }            }}

Java multithreading callable and future classes

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.