Home > Java > javaTutorial > body text

How to use thread pool in Java 7 to handle return results of multi-threaded tasks

PHPz
Release: 2023-07-29 10:17:29
Original
1413 people have browsed it

How to use thread pools in Java 7 to process the return results of multi-threaded tasks

When developing Java applications, it is often necessary to process multi-threaded tasks and obtain the return results of threads. Using a thread pool can better manage thread resources and be able to handle the return results of multi-threaded tasks. This article will introduce how to use thread pools to handle the return results of multi-threaded tasks in Java 7, and provide code examples.

Thread pool is a mechanism for managing and reusing thread resources. Through the thread pool, you can create threads when needed instead of creating a new thread every time you start a thread. Thread pools can improve application performance and reduce the overhead of thread creation and destruction.

In Java 7, you can use the Executors class to create a thread pool. The following is a sample code to create a thread pool:

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

The above code will create a thread pool containing 10 threads. Next, we will use the thread pool to perform multi-threaded tasks and obtain the return results of the threads.

Suppose there is a list of tasks, each of which needs to be executed in an independent thread and the result of the execution is returned. The following is an example task class:

public class Task implements Callable<String> {
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public String call() throws Exception {
        // 执行任务的代码
        Thread.sleep(1000);
        return "Task " + name + " has been completed";
    }
}
Copy after login

In the above code, the Task class implements the Callable interface and specifies the type of return result as String. call()The method contains the code of the task to be performed. In this example, the thread simply sleeps for 1 second and returns a string.

Next, we will use the thread pool to perform these tasks and obtain the return results of the thread. The following is a sample code that uses a thread pool to process tasks:

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        
        List<Future<String>> results = new ArrayList<>();
        
        for (int i = 0; i < 10; i++) {
            Task task = new Task("Task " + i);
            results.add(executor.submit(task));
        }
        
        executor.shutdown();
        
        for (Future<String> result : results) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
Copy after login

In the above code, a thread pool is first created, and then an ArrayList is created to store FutureObjects, these objects represent the status and results of thread tasks.

Next, 10 Task instances are created through a loop, submitted to the thread pool, and the Future object is added to the result list.

Then, call the shutdown() method of the thread pool to shut down the thread pool.

Finally, traverse the result list through another loop, use the get() method of the Future object to obtain the return result of the thread, and print the result.

Run the above code, we will get output similar to the following:

Task 0 has been completed
Task 1 has been completed
Task 2 has been completed
Task 3 has been completed
Task 4 has been completed
Task 5 has been completed
Task 6 has been completed
Task 7 has been completed
Task 8 has been completed
Task 9 has been completed
Copy after login

The above code demonstrates how to use the thread pool to handle the return results of multi-threaded tasks. By using the thread pool, we can better manage thread resources and easily obtain the return results of the thread.

Please note that the thread pool and related classes of Java 7 are used in the examples in this article. In Java 8, more powerful and flexible thread pools and concurrency utility classes have been introduced. If you are developing in Java 8 and above, it is recommended to use Java 8's concurrency tool class to handle the return results of multi-threaded tasks.

The above is the detailed content of How to use thread pool in Java 7 to handle return results of multi-threaded tasks. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!