在使用Executor框架执行多线程任务时,可以通过给每个Callable对象设置一个标识符来确定返回结果来自于哪个线程。具体步骤如下:
1. 创建一个Callable对象时,给它设置一个标识符,例如:
```
final String taskId = "task1";
Callable task1 = new Callable() {
public Integer call() throws Exception {
// 执行任务1
return 1;
}
};
```
2. 在获取Future对象时,将Callable对象的标识符与Future对象关联起来,例如:
```
Map, String> futureMap = new HashMap<>();
futureMap.put(executor.submit(task1), taskId);
```
3. 遍历Future对象列表时,根据Future对象获取对应的标识符,例如:
```
for (Future future : futures) {
try {
int result = future.get();
String taskId = futureMap.get(future);
System.out.println("线程" + taskId + "返回结果:" + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
```
完整示例代码如下:
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class MultiThreadDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
final String taskId1 = "task1";
Callable task1 = new Callable() {
public Integer call() throws Exception {
// 执行任务1
return 1;
}
};
final String taskId2 = "task2";
Callable task2 = new Callable() {
public Integer call() throws Exception {
// 执行任务2
return 2;
}
};
Map, String> futureMap = new HashMap<>();
futureMap.put(executor.submit(task1), taskId1);
futureMap.put(executor.submit(task2), taskId2);
List> futures = new ArrayList<>(futureMap.keySet());
for (Future future : futures) {
try {
int result = future.get();
String taskId