Home Java javaTutorial java-concurrency-Callable, Future and FutureTask

java-concurrency-Callable, Future and FutureTask

Jan 19, 2017 am 11:56 AM

There are two ways to create a thread, one is to directly inherit Thread, and the other is to implement the Runnable interface

Difference: The interface can implement multiple inheritance

The defect is: after executing the task The execution result cannot be obtained afterwards

Callable and Runnable

java.lang.Runnable

[code]public interface Runnable {
    public abstract void run();
}
Copy after login

Because the return value of the run() method is void type, it cannot be obtained after the task is executed. Return no results.

java.util.concurren

[code]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;
}
Copy after login

Generic interface, the type returned by the call() function is the V type passed in

Generally used in conjunction with ExecutorService , several overloaded versions of the submit method are declared in the ExecutorService interface

[code]<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
Copy after login

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. This method will block until the task returns the result.

[code]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;
}
Copy after login

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.

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

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

get(long timeout, TimeUnit unit) is used to obtain the execution result. If the result is not obtained within the specified time, null will be returned directly.

In other words, Future provides three functions:

1) Determine whether the task is completed;

2) Ability to interrupt the task;

3) Ability to Get task execution results.

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

FutureTask

[code]public class FutureTask<V> implements RunnableFuture<V>
Copy after login
[code]public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}
Copy after login
[code]public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
Copy after login

In fact, FutureTask is the only implementation class of the Future interface.

Example

[code]public class Test {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}
Copy after login
[code]public class Test {
    public static void main(String[] args) {
        //第一种方式
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();

        //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
        /*Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        Thread thread = new Thread(futureTask);
        thread.start();*/

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}
Copy after login

If you use Future for cancelability but do not provide usable results, you can declare Future

The above is java-concurrency-Callable , Future and FutureTask content, please pay attention to the PHP Chinese website (www.php.cn) for more related content!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

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 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...

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 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 to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

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...

See all articles