search
HomeJavajavaTutorialDetailed introduction to Callable and Future in Java multithreading (code example)

This article brings you a detailed introduction (code example) about Callable and Future in Java multi-threading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The reason why Callable and Future appear

There are two ways to create a thread, one is to directly inherit Thread, and the other is to implement the Runnable interface.
These two methods have a flaw: the execution results cannot be obtained after completing the task.
If you need to obtain the execution results, you must achieve the effect through shared variables or thread communication, which is more troublesome to use.
Since Java 1.5, Callable and Future have been provided, through which the task execution results can be obtained after the task execution is completed.

Introduction to Callable and Future

The Callable interface represents a piece of code that can be called and returns a result; the Future interface represents an asynchronous task, which is the future given by the task that has not yet been completed. result. So Callable is used to generate results, and Future is used to obtain results.
The Callable interface uses generics to define its return type. The Executors class provides some useful methods to execute tasks within the Callable in the thread pool. Since the Callable task is parallel (parallel means that the whole thing looks parallel, in fact, only one thread is executing at a certain point in time), we must wait for the result it returns.
java.util.concurrent.Future object solves this problem for us. After the thread pool submits the Callable task, a Future object is returned. You can use it to know the status of the Callable task and get the execution result returned by the Callable. Future provides the get() method so that we can wait for the Callable to end and obtain its execution results.

Callable and Runnable

java.lang.Runnable, it is an interface, and only one run() method is declared in it:

public interface Runnable {
    public abstract void run();
}

Since the return value of the run() method is void type, no results can be returned after the task is executed.

Callable is located under the java.util.concurrent package. It is also an interface, and only one method is declared in it, but this method is called call():

public interface Callable<v> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}</v>

This is a For generic interfaces, the type returned by the call() function is the V type passed in.

Use of Callable

Generally, it is used in conjunction with ExecutorService. Several overloaded versions of the submit method are declared in the ExecutorService interface.

<t> Future<t> submit(Callable<t> task);
<t> Future<t> submit(Runnable task, T result);
Future> submit(Runnable task);</t></t></t></t></t>

The parameter type in the first submit method is Callable.

For the time being, you only need to know that Callable is generally used in conjunction with ExecutorService. The specific usage method will be described later.

Generally, we use the first submit method and the third submit method, and the second submit method is rarely used.

Future

Future is to cancel the execution result of a specific Runnable or Callable task, query whether it is completed, and obtain the result. If necessary, you can obtain the execution result through the get method, which will block until the task returns the result.

The Future class is located under the java.util.concurrent package. It is an interface:

public interface Future<v> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}</v>
declares 5 methods in the Future interface. The function of each method is explained below.
  • The cancel method is used to cancel the task. If the task cancellation is successful, it returns true. If the task cancellation fails, it returns false. The parameter mayInterruptIfRunning indicates whether it is allowed to cancel tasks that are being executed but have not been completed. If set to true, it means that tasks in the process of execution can be canceled. If the task has been completed, whether mayInterruptIfRunning is true or false, this method will definitely return false, that is, if the completed task is canceled, it will return false; if the task is being executed, if mayInterruptIfRunning is set to true, it will return true, if mayInterruptIfRunning is set to false , then return false; if the task has not been executed, then whether mayInterruptIfRunning is true or false, it will definitely return true.

  • The isCancelled method indicates whether the task was successfully canceled. If the task is successfully canceled before the task is completed normally, it returns true.

  • isDone method indicates whether the task has been completed. If the task is completed, it returns true;

  • get() method is used to obtain the execution result. This method will block and will wait until the task execution is completed before returning;

  • get(long timeout, TimeUnit unit) is used to obtain the execution result. If it has not been obtained within the specified time, When the result is reached, null is returned directly.

Future provides three functions:
  1. to determine whether the task is completed;

  2. to be able to interrupt Task;

  3. can obtain the task execution results.

    Because Future is just an interface, it cannot be used directly to create objects, so there is the following FutureTask.

    FutureTask

    FutureTask implements the RunnableFuture interface. The definition of this interface is as follows:
public interface RunnableFuture<v> extends Runnable, Future<v> {  
    void run();  
}</v></v>

You can see that this interface implements the Runnable and Future interfaces. The specific implementation in the interface is implemented by FutureTask. The two construction methods of this class are as follows:

public FutureTask(Callable<v> callable) {  
        if (callable == null)  
            throw new NullPointerException();  
        sync = new Sync(callable);  
    }  
    public FutureTask(Runnable runnable, V result) {  
        sync = new Sync(Executors.callable(runnable, result));  
    }</v>

如上提供了两个构造函数,一个以Callable为参数,另外一个以Runnable为参数。这些类之间的关联对于任务建模的办法非常灵活,允许你基于FutureTask的Runnable特性(因为它实现了Runnable接口),把任务写成Callable,然后封装进一个由执行者调度并在必要时可以取消的FutureTask。

FutureTask可以由执行者调度,这一点很关键。它对外提供的方法基本上就是Future和Runnable接口的组合:get()、cancel、isDone()、isCancelled()和run(),而run()方法通常都是由执行者调用,我们基本上不需要直接调用它。

FutureTask的例子
public class MyCallable implements Callable<string> {  
    private long waitTime;   
    public MyCallable(int timeInMillis){   
        this.waitTime=timeInMillis;  
    }  
    @Override  
    public String call() throws Exception {  
        Thread.sleep(waitTime);  
        //return the thread name executing this callable task  
        return Thread.currentThread().getName();  
    }  

}</string>
public class FutureTaskExample {  
     public static void main(String[] args) {  
        MyCallable callable1 = new MyCallable(1000);                       // 要执行的任务  
        MyCallable callable2 = new MyCallable(2000);  

        FutureTask<string> futureTask1 = new FutureTask<string>(callable1);// 将Callable写的任务封装到一个由执行者调度的FutureTask对象  
        FutureTask<string> futureTask2 = new FutureTask<string>(callable2);  

        ExecutorService executor = Executors.newFixedThreadPool(2);        // 创建线程池并返回ExecutorService实例  
        executor.execute(futureTask1);  // 执行任务  
        executor.execute(futureTask2);    

        while (true) {  
            try {  
                if(futureTask1.isDone() && futureTask2.isDone()){//  两个任务都完成  
                    System.out.println("Done");  
                    executor.shutdown();                          // 关闭线程池和服务   
                    return;  
                }  

                if(!futureTask1.isDone()){ // 任务1没有完成,会等待,直到任务完成  
                    System.out.println("FutureTask1 output="+futureTask1.get());  
                }  

                System.out.println("Waiting for FutureTask2 to complete");  
                String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);  
                if(s !=null){  
                    System.out.println("FutureTask2 output="+s);  
                }  
            } catch (InterruptedException | ExecutionException e) {  
                e.printStackTrace();  
            }catch(TimeoutException e){  
                //do nothing  
            }  
        }  
    }  
}</string></string></string></string>

The above is the detailed content of Detailed introduction to Callable and Future in Java multithreading (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools