Home > Java > javaTutorial > body text

How to efficiently use thread pools to implement concurrent programming in Java?

王林
Release: 2024-05-02 08:27:01
Original
1185 people have browsed it

How to efficiently use thread pools to implement concurrent programming in Java? Create a thread pool and pre-allocate a set of threads. Submit the task to the thread pool, and the thread obtains the task from the queue for execution. Threads in the thread pool are responsible for acquiring and executing tasks in the queue, and completed tasks are automatically deleted from the queue.

如何在 Java 中高效使用线程池实现并发编程?

How to efficiently use thread pools to implement concurrent programming in Java

Introduction to thread pools

Thread pool is a special data structure used to manage threads. It pre-allocates a set of threads and allocates threads from them as needed to perform tasks. This avoids frequent creation and destruction of threads, thereby improving performance and efficiency.

Java Thread Pool

The thread pool in Java can be created in the following ways:

ExecutorService executor = Executors.newFixedThreadPool(5);
Copy after login

Among them, newFixedThreadPool is created A fixed-size thread pool with 5 threads.

Task Submission

Tasks can be submitted to the thread pool in the following ways:

executor.submit(task);
Copy after login

Among them, task is to be executed task.

Task Execution

Threads in the thread pool are responsible for getting tasks from the queue and executing them. Completed tasks are automatically removed from the queue.

Practical case

The following is an example of using a thread pool for concurrent processing:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolExample {

    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 创建任务列表
        List<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            numbers.add(i);
        }

        // 将任务提交到线程池
        List<Future<Integer>> futures = new ArrayList<>();
        for (int number : numbers) {
            Future<Integer> future = executor.submit(() -> {
                return number * number;
            });
            futures.add(future);
        }

        // 获取任务结果
        List<Integer> results = new ArrayList<>();
        for (Future<Integer> future : futures) {
            try {
                results.add(future.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池
        executor.shutdown();
    }
}
Copy after login

In this example, ThreadPoolExample Class:

  1. Create a thread pool with 5 threads (executor).
  2. Create a list of 10,000 numbers (numbers).
  3. Submit each number as a task to the thread pool (executor.sumbit).
  4. Get the results of each task and add them to results.
  5. Close the thread pool.

The above is the detailed content of How to efficiently use thread pools to implement concurrent programming in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template