Comparison of runnable, callable, future and futuretask in Java

Comparison of runnable, callable, future and futuretask in Java

There are several thread related classes or interfaces in Java, such as runnable, callable, future and futuretask, which are also important concepts in Java. Let's understand their functions and differences through the following simple examples.

Runnable

Runnable should be the most familiar interface. It has only one run () function to write time-consuming operations in it. This function has no return value. Then use a thread to execute the runnable to realize multithreading. After calling the start() function, the thread class executes the run() function of runnable. Runnable's statement is as follows:

Callable

The function of callable is similar to that of runnable. Callable has a call () function, but the call () function has a return value, while runnable's run () function cannot return the result to the client. Callable's statement is as follows:

You can see that this is a generic interface, and the type returned by the call () function is the V type passed in by the client.

Future

Executor is the scheduling container of runnable and callable. Future is to cancel, query whether the execution result of a specific runnable or callable task is completed, obtain the result, and set the result. The get method blocks until the task returns a result (Introduction to future). Future declares as follows:

FutureTask

Futuretask is a runnablefuture < V >, and runnablefuture implements runnbale and Futrue < V >:

RunnableFuture

In addition, futuretask can also wrap runnable and callable < V > and inject dependencies by the constructor.

As you can see, runnable injection will be executed by executors The callable () function is converted to callable type, that is, futuretask will eventually execute callable type tasks. The implementation of the adaptation function is as follows:

Runnableadapter adapter

Because futuretask implements runnable, it can be executed directly through thread wrapper or submitted to executeservice for execution. You can also get the execution result directly through the get () function, which will block until the result is returned.

Therefore, futuretask is a combination of future, runnable and callable (if it is runnable, it will eventually be converted to callable).

Complete example:

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>