Home > Java > javaTutorial > How to use thread pool to implement task loop execution and return result processing in Java 7

How to use thread pool to implement task loop execution and return result processing in Java 7

PHPz
Release: 2023-07-30 12:46:52
Original
955 people have browsed it

How to use thread pool in Java 7 to implement cyclic execution of tasks and return result processing

In Java, thread pool is an important multi-threaded programming technology, which can reduce the overhead of creating threads. In higher cases, thread reuse and management are provided. Through the thread pool, multiple tasks can be submitted to the thread pool for execution. The thread pool maintains a group of threads in the background and schedules and manages the execution of these threads according to specific policies. In Java 7, the use of thread pools has become simpler and more convenient. This article will introduce how to use the thread pool in Java 7 to implement cyclic execution of tasks and return result processing.

1. Create a thread pool
In Java 7, you can use the ThreadPoolExecutor class to create a thread pool. ThreadPoolExecutor provides a variety of construction methods to customize the number of core threads, maximum number of threads, task queue, rejection policy and other parameters of the thread pool. The following is a simple example code for creating a thread pool:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个固定大小为5的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        
        // ...
        
        // 关闭线程池
        executorService.shutdown();
    }
}
Copy after login

2. Submit the task and get the return result
After creating the thread pool, we can submit the task to the thread pool through the submit() method Execute in the task and obtain the return result of the task through the Future object. The following is a sample code:

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 executorService = Executors.newFixedThreadPool(5);
        
        // 提交任务并获取Future对象
        Future<String> future = executorService.submit(() -> {
            // 任务的具体逻辑
            // 这里以延时1秒返回结果为例
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, World!";
        });
        
        try {
            // 获取任务的返回结果
            String result = future.get();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        executorService.shutdown();
    }
}
Copy after login

3. Loop execution of tasks
In some scenarios, we may need to loop through a set of tasks and obtain the return results of each task. You can use a for loop to submit tasks, and use a List to save the Future object for each task. The following is a sample code:

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 executorService = Executors.newFixedThreadPool(5);
        
        // 保存每个任务的Future对象
        List<Future<String>> futures = new ArrayList<>();
        
        // 循环执行10个任务
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            Future<String> future = executorService.submit(() -> {
                // 任务的具体逻辑
                // 这里以延时1秒返回结果为例
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "Task-" + taskId + " is completed.";
            });
            futures.add(future);
        }
        
        // 获取每个任务的返回结果
        for (Future<String> future : futures) {
            try {
                String result = future.get();
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        executorService.shutdown();
    }
}
Copy after login

4. Summary
By using the thread pool, the cyclic execution of tasks and return result processing can be implemented in Java 7. When creating a thread pool, you can adjust the parameters of the thread pool according to specific needs; when submitting a task, you can submit the task through the submit() method, and use the Future object to obtain the return result of the task; when you need to execute the task in a loop, You can use a for loop to submit tasks, and use a List to save the Future object for each task. By rationally using the thread pool, system resources can be fully utilized and the execution efficiency of the program can be improved.

The above is the detailed content of How to use thread pool to implement task loop execution and return result processing in Java 7. For more information, please follow other related articles on the PHP Chinese website!

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