FutureTask and Callable: Difference in Java Concurrency
In Java concurrent programming, FutureTask
and Callable
plays an important role, and the difference between them is:
Callable
Runnable
, but with a return value. call()
method to return the result of the task. FutureTask
Future
interface, representing an asynchronous task that is being executed or completed. Callable
object to manage the details of task execution. get()
) and check whether the task is completed (isDone()
). Difference
Features | Callable | FutureTask |
---|---|---|
Return value | No return value | Return task results |
Multiple results supported | Not supported | Support multiple FutureTask Represents the same Callable
|
Not supported | Supports canceling the task by calling | cancel()
|
call() Processing in the method
|
FutureTask Provides the get() method to handle exceptions
|
Practical Case
Suppose we have a simple task to calculate the first n elements of the Fibonacci sequence.Callable implementation:
import java.util.concurrent.Callable; public class FibonacciCallable implements Callable<Integer[]> { private int n; public FibonacciCallable(int n) { this.n = n; } @Override public Integer[] call() { Integer[] fibSequence = new Integer[n]; fibSequence[0] = 0; fibSequence[1] = 1; for (int i = 2; i < n; i++) { fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2]; } return fibSequence; } }
FutureTask implementation:
import java.util.concurrent.FutureTask; import java.util.concurrent.ExecutionException; public class FibonacciFutureTask { public static void main(String[] args) { int n = 10; FibonacciCallable callable = new FibonacciCallable(n); FutureTask<Integer[]> futureTask = new FutureTask<>(callable); new Thread(futureTask).start(); Integer[] fibSequence; try { fibSequence = futureTask.get(); // 等待任务完成并获取结果 } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } System.out.println("Fibonacci sequence upto " + n + " elements:"); for (Integer fib : fibSequence) { System.out.print(fib + " "); } } }
Callable to define tasks and use
FutureTask to manage task execution. By calling the
get() method, we can get the Fibonacci sequence after the task is completed.
The above is the detailed content of What is the difference between FutureTask and Callable in Java function concurrency and multi-threading?. For more information, please follow other related articles on the PHP Chinese website!