Use ExecutorService to manage the thread pool and execute tasks, and use FutureTask to asynchronously execute tasks and retrieve their results. ExecutorService provides methods such as execute() and submit(), and FutureTask provides get(), isDone(), and cancel() methods. Practical examples show how to use them to calculate numbers in the Fibonacci sequence in parallel.
The use of ExecutorService and FutureTask in Java parallel programming
Introduction
ExecutorService and FutureTask are useful tools for parallel programming in Java. ExecutorService allows you to manage a set of threads, while FutureTask allows you to execute tasks asynchronously and retrieve their results.
ExecutorService
ExecutorService is an interface that represents a collection of executable thread tasks. You can create different implementations of ExecutorService using:
ExecutorService executorService = Executors.newFixedThreadPool(5);
where 5 represents the number of threads in the thread pool.
ExecutorService provides the following methods to execute tasks:
-
execute(Runnable task)
: Execute a Runnable task. -
submit(Runnable task)
: Execute a Runnable task and return a value. -
submit(Callable<t> task)</t>
: Execute a Callable task and return a value.
FutureTask
FutureTask is a wrapper around a Callable task that allows you to execute a task asynchronously and retrieve its results later. You can create a FutureTask using the following method:
FutureTask<String> futureTask = new FutureTask<>(() -> "Hello, world!");
where () -> "Hello, world!"
is the Callable task to be executed.
FutureTask provides the following methods to retrieve task results:
-
get()
: Blocks waiting for the task to complete and returns the result. -
isDone()
: Check whether the task has been completed. -
cancel(boolean mayInterruptIfRunning)
: Cancel the task (if possible).
Practical case
Consider a program that calculates the Fibonacci sequence. We can use ExecutorService and FutureTask to calculate multiple Fibonacci numbers in parallel:
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; class FibonacciTask implements Callable<Long> { private int n; public FibonacciTask(int n) { this.n = n; } @Override public Long call() { long a = 0; long b = 1; for (int i = 0; i < n; i++) { long temp = a; a = b; b = temp + b; } return a; } } public class Main { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(4); FutureTask<Long>[] tasks = new FutureTask[10]; // 创建并提交任务 for (int i = 0; i < 10; i++) { tasks[i] = new FutureTask<>(new FibonacciTask(i)); executorService.submit(tasks[i]); } // 获取并打印结果 for (int i = 0; i < 10; i++) { try { System.out.println("斐波那契数列第 " + i + " 项:" + tasks[i].get()); } catch (Exception e) { e.printStackTrace(); } } // 关闭 ExecutorService executorService.shutdown(); } }
In this example, we created an ExecutorService and submitted 10 FibonacciTask tasks. Each task calculates a number in the Fibonacci sequence. Using FutureTask, we are able to execute these tasks asynchronously and get their results later.
The above is the detailed content of The use of ExecutorService and FutureTask in Java parallel programming. For more information, please follow other related articles on the PHP Chinese website!

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.