可以使用Java中的Executor框架来实现多线程执行不同任务,并获取每个线程的返回结果。具体步骤如下:
1. 创建一个ExecutorService对象,例如:
```
ExecutorService executor = Executors.newFixedThreadPool(5);
```
这里创建了一个固定大小为5的线程池。
2. 创建多个Callable对象,每个Callable对象代表一个需要执行的任务,并返回一个结果。例如:
```
Callable task1 = new Callable() {
public Integer call() throws Exception {
// 执行任务1
return 1;
}
};
Callable task2 = new Callable() {
public Integer call() throws Exception {
// 执行任务2
return 2;
}
};
```
3. 将所有任务添加到线程池中,并获取Future对象列表。例如:
```
List> futures = new ArrayList<>();
futures.add(executor.submit(task1));
futures.add(executor.submit(task2));
// 添加更多任务...
```
4. 遍历Future对象列表,获取每个线程的返回结果。例如:
```
for (Future future : futures) {
try {
int result = future.get();
System.out.println("线程返回结果:" + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
```
完整示例代码如下:
```
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class MultiThreadDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
Callable task1 = new Callable() {
public Integer call() throws Exception {
// 执行任务1
return 1;
}
};
Callable task2 = new Callable() {
public Integer call() throws Exception {
// 执行任务2
return 2;
}
};
List> futures = new ArrayList<>();
futures.add(executor.submit(task1));
futures.add(executor.submit(task2));
for (Future future : futures) {
try {
int result = future.get();
System.out.println("线程返回结果:" +