阅读量:121
Java线程池并发调用接口的方法可以通过以下步骤实现:
- 创建一个线程池对象,可以使用
ExecutorService的工厂方法创建,如newFixedThreadPool(int nThreads)创建固定线程数的线程池。 - 定义一个实现
Callable接口的任务类,该任务类负责调用接口的方法,并返回结果。 - 将任务提交给线程池,可以使用
submit(Callable方法提交任务,并返回task) Future对象,通过该对象可以获取任务的执行结果。 - 可以使用
Future对象的get()方法获取任务的执行结果,该方法是阻塞的,直到任务执行完成并返回结果。 - 可以使用
List来保存所有任务的> Future对象,然后遍历列表,使用get()方法获取每个任务的执行结果。
下面是一个简单的示例代码:
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务并获取Future对象
Future future1 = executor.submit(new MyTask("Task 1"));
Future future2 = executor.submit(new MyTask("Task 2"));
Future future3 = executor.submit(new MyTask("Task 3"));
// 获取任务的执行结果
try {
String result1 = future1.get();
String result2 = future2.get();
String result3 = future3.get();
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
System.out.println("Result 3: " + result3);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// 关闭线程池
executor.shutdown();
}
}
class MyTask implements Callable {
private String name;
public MyTask(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
// 调用接口的方法并返回结果
return "Hello from " + name;
}
}
在上面的示例中,我们创建了一个固定线程数为5的线程池,并提交了3个任务给线程池执行。然后通过Future对象获取任务的执行结果,并打印出来。最后关闭线程池。