laitimes

Multithreaded - There are Callable results returned

author:IT Knowledge Sharing Officer

background

The simplest multithreading is Runnable, and the biggest feature is that no results are returned.

So how can there be a return result? Use Callable.

Official documentation - Callable

java           

Copy the code

@FunctionalInterfacepublicinterfaceCallable<V>

A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

A task that returns results and may throw an exception. The implementer defines a method with no parameters, called a call.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

The Callable interface is similar to Runnable in that both are designed for classes where an instance might be executed by another thread. However, Runnable does not return results and cannot throw a checked exception.

The Executors class contains utility methods to convert from other common forms to Callable classes.

The Executors class contains practical methods that convert from other common forms to the Callable class.

Source code - Callable

java           

Copy the code

publicinterfaceCallable<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; The biggest difference with Runnable is whether there is a return result}

The biggest difference with Runnable is that there is returned data.

Callable effect

Callable is an interface in Java that is located in the java.util.current package. Its main role is to allow you to execute tasks that return results in a multithreaded environment, and to be able to get the results of task execution or handle exceptions during task execution.

The main features and functions are as follows:

  1. Returnable Results: Unlike the Runnable interface, Callable can return one result. The type of this result is specified by generic parameters, for example Callable <Integer>can return an integer result.
  2. Exception handling: Callable's call method can throw exceptions that you can catch and handle appropriately.
  3. Multi-threaded task execution: You can submit Callable tasks to the ExecutorService's thread pool for execution, which allows you to execute tasks in parallel in multiple threads.
  4. Get task results: With the Future object, you can get the results of task execution asynchronously. Future provides methods to wait for the task to complete and get its result.
  5. Blocking wait: If you need to wait for the task to complete, you can use Future's get method, which blocks the current thread until the task completes and returns the result.

Here's a simple example of how to use Callable and ExecutorService to perform a task that returns results:

java           

Copy the code

import java.util.concurrent.*; publicclassCallableExample {publicstaticvoidmain(String[] args)throws InterruptedException, ExecutionException {ExecutorServiceexecutorService= Executors.newSingleThreadExecutor(); Callable<Integer> task = () -> {// Perform time-consuming operations here Thread.sleep(2000); return42; }; Future future<Integer> = executorService.submit(task);// Some other work can be done here // Get the task execution result, if the task has not completed, it will block the current thread until it completes intresult= future.get(); System.out.println("Task result:" + result); executorService.shutdown(); }}

Overall, Callable makes multithreaded programming more flexible, allowing you to perform tasks that return results, as well as the ability to handle exceptions and get the execution results of tasks. This is useful for applications that require concurrent processing of tasks.

With Runnable, why Callable?

While both Runnable and Callable are used to perform tasks in a multithreaded environment, there are some important differences and use cases between them, which explains why Java provides these two different interfaces.

Here are some differences and reasons why you should use Callable:

  1. Return Results:
  2. Runnable returns no results, and its run method has no return value. If you need a task to return a result after execution, you must use another mechanism, such as an instance variable or a shared queue, to get the result.
  3. Callable can return a result of the type specified by a generic parameter. This makes the results of the task easier to access and process.
  4. Exception handling:
  5. Runnable's run method cannot throw a checked exception (except with the deprecated Thread.setDefaultUncaughtExceptionHandler method), so it is generally not suitable for tasks that might throw an exception.
  6. Callable's call method can throw checked exceptions, which means you can more easily handle exceptions during task execution.
  7. Future object:
  8. After the Callable task is submitted, it returns a Future object that you can use to get the result of the task asynchronously. This is useful for situations where you need to wait for a task to complete, and you can block waiting for a result when needed.
  9. Runnable doesn't have a built-in mechanism to get the execution results of a task, so you'll need to implement a way to get the results yourself.
  10. Applicability:
  11. Callable is generally better suited for situations where you need to execute, wait, and process the results of a task, especially in concurrent programming and multithreaded environments.
  12. Runnable is generally better suited for simple tasks that do not require returning results or handling exceptions during task execution.

To sum up, both Callable and Runnable have their unique uses and advantages. Which interface you choose depends on your specific needs, and if you need task return results, handle exceptions, and more advanced task control, then Callable may be more suitable for you. If you're just performing simple tasks without returning results or handling exceptions, then Runnable might be enough.

Callable has advantages over Runnable

Callable has some distinct advantages over Runnable, especially in terms of requiring richer multi-threaded task processing and result acquisition. Here are some of the advantages of Callable over Runnable:

  1. Returning Results: One of the biggest advantages is that Callable allows tasks to return a result. This means that the task can perform some calculation or operation and return the result to the caller. This is useful when dealing with concurrent tasks that require calculations or produce results.
  2. Exception handling: Callable's call method can throw an examined exception, so it's better suited for tasks where exceptions might occur. This allows you to better handle error conditions during task execution.
  3. Future object: After the Callable task is submitted, it returns a Future object, allowing you to get the result of the task asynchronously. This is useful for situations where you need to wait for a task to complete and get the results when needed. You can use Future's method to wait for the task to complete, check if the task has completed, get the result, or cancel the execution of the task.
  4. Richer task control: The Callable interface, combined with Future, provides more task control. You can cancel the execution of tasks, set a timeout for tasks, and perform multiple tasks together with multiple Future objects.
  5. Generic support: Callable uses generics to specify the type of returned result, which increases type safety. You can explicitly specify the type of data returned by the task, making your code more maintainable and readable.

In summary, Callable offers more features and control options than Runnable, making multithreaded programming more flexible and powerful. However, it should also be noted that the use of Callable requires more code and processing, so in the case of simple tasks, it is necessary to choose the appropriate interface.