Sobes.tech
Junior — Middle

Can you name interfaces similar to Runnable used for defining executable tasks?

sobes.tech AI

Answer from AI

In Java, besides the Runnable interface, which defines a task without a return value, the Callable<V> interface is often used. It is similar to Runnable, but allows returning a result and throwing checked exceptions.

Example:

Callable<Integer> task = () -> {
    // perform task
    return 123;
};

For asynchronous programming and working with threads, interfaces from the java.util.concurrent package can also be used, such as FutureTask, which implements Runnable and allows obtaining the result of the task.

In summary:

  • Runnable — task without a result
  • Callable<V> — task with a result and the ability to throw exceptions
  • FutureTask<V> — a wrapper for Callable or Runnable with the ability to get the result and control execution.