Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What do Callable, Future and FutureTask mean in Java multithreading

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you what the meaning of Callable, Future and FutureTask in Java multithreading is, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's go to know it together.

Foreword:

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

A drawback of both methods is that the execution result cannot be obtained after the task has been executed.

If you need to get the execution results, you must share variables or use thread communication to achieve the results, which is more troublesome to use.

Since Java 1.5, Callable and Future have been provided, through which the execution results of the task can be obtained after the task has been executed.

1 Callable introduction

The Callable interface represents a piece of code that can be called and returns the result; the Future interface represents an asynchronous task, which is the future result of a task that has not yet been completed. So Callable is used to produce results, and Future is used to get results.

The Callable interface uses generics to define its return type. The Executors class provides some useful ways to perform tasks within the Callable in the thread pool. Because the Callable task is parallel (parallel means that the whole appears to be parallel, but there is only one thread executing at some point in time), we have to wait for the result it returns.

The java.util.concurrent.Future object solves this problem for us. The thread pool returns a Future object after submitting the Callable task, which can be used to know the status of the Callable task and get the execution result returned by Callable. Future provides a get () method that allows us to wait for Callable to finish and get its execution result.

2 Future introduction 2.1 declare the method in the Future interface

Declare five methods in the Future interface and explain the role of each method in turn:

2.2 Future provides three functions

1) determine whether the task is completed or not

2) can interrupt the task

3) the result of task execution can be obtained.

Because Future is only an interface, it cannot be used directly to create objects, so you have the following FutureTask.

3 FutureTask

Let's first look at the implementation of FutureTask:

Public class FutureTask implements RunnableFuture

The FutureTask class implements the RunnableFuture interface. Let's take a look at the implementation of the RunnableFuture interface:

Public interface RunnableFuture extends Runnable, Future {void run ();}

You can see that RunnableFuture inherits the Runnable interface and the Future interface, while FutureTask implements the RunnableFuture interface. So it can be executed by the thread either as Runnable or as Future to get the return value of Callable.

FutureTask provides two constructors:

Public FutureTask (Callable callable) {} public FutureTask (Runnable runnable, V result) {}

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

4. Future and FutureTask use Callable+Future to get the execution result public class CallableFutureTest {public static void main (String [] args) {/ / create thread pool ExecutorService es = Executors.newSingleThreadExecutor (); / / create Callable object task CallableDemo calTask = new CallableDemo (); / / submit the task and get the execution result Future future = es.submit (calTask) / / close thread pool es.shutdown (); try {Thread.sleep (2000); System.out.println ("main thread is performing other tasks") If (future.get ()! = null) {/ / output the obtained result System.out.println ("future.get ()-- >" + future.get ());} else {/ / output the obtained result System.out.println ("future.get () does not get the result") } catch (Exception e) {e.printStackTrace ();} System.out.println ("main thread is completing execution");}} class CallableDemo implements Callable {private int sum; @ Override public Integer call () throws Exception {System.out.println ("Callable child thread starts to calculate!") ; Thread.sleep (2000); for (int I = 0; I)

< 100; i++) { sum = sum + i; } System.out.println("Callable子线程计算结束!"); return sum; }} Callable子线程开始计算啦! Callable子线程计算结束! 主线程在执行其他任务 future.get()-->

4950

The main thread is completing execution.

4.2 use Callable+Future to get execution result public class CallableFutureTest {public static void main (String [] args) {/ create thread pool / / ExecutorService es = Executors.newSingleThreadExecutor (); / create Callable object task / / CallableDemo calTask=new CallableDemo (); / submit task and get execution result / / Future future = es.submit (calTask) / close thread pool / / es.shutdown (); / / create thread pool ExecutorService es = Executors.newSingleThreadExecutor (); / / create Callable object task CallableDemo calTask = new CallableDemo (); / / create FutureTask FutureTask futureTask = new FutureTask (calTask); / / execute task es.submit (futureTask) / / close thread pool es.shutdown (); try {Thread.sleep (2000); System.out.println ("main thread is performing other tasks") If (futureTask.get ()! = null) {/ / output the obtained result System.out.println ("futureTask.get ()-- >" + futureTask.get ());} else {/ / output the obtained result System.out.println ("futureTask.get () does not get the result") } catch (Exception e) {e.printStackTrace ();} System.out.println ("main thread is completing execution");}} class CallableDemo implements Callable {private int sum; @ Override public Integer call () throws Exception {System.out.println ("Callable child thread starts to calculate!") ; Thread.sleep (2000); for (int I = 0; I)

< 100; i++) { sum = sum + i; } System.out.println("Callable子线程计算结束!"); return sum; }} Callable子线程开始计算啦! Callable子线程计算结束! 主线程在执行其他任务 futureTask.get()-->

4950

The main thread is completing execution.

But in fact, the two methods are ultimately the same:

The first way, Callable+Future, is finally implemented in the form of Callable+FutureTask.

In the first way: Future future = executor.submit (task) is called

Let's look at the source code of executor.submit (task):

/ / java.util.concurrent.AbstractExecutorService class / * * @ throws RejectedExecutionException {@ inheritDoc} * @ throws NullPointerException {@ inheritDoc} * / public Future submit (Callable task) {if (task = = null) throw new NullPointerException (); RunnableFuture ftask = newTaskFor (task); / / you can see that a RunnableFuture interface implementation class execute (ftask) is actually created inside submit (Callable task) in the source code Return ftask;}

And FutureTask is the implementation class of RunnableFuture, so take a look at what is done in newTaskFor (Callable callable):

Protected RunnableFuture newTaskFor (Callable callable) {return new FutureTask (callable);} these are all the contents of the article "what are Callable, Future, and FutureTask in Java multithreading?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report