java 多线程返回结果_JAVA 线程执行返回结果

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class TaskWithResult implements Callable {

private int id ;

public TaskWithResult(int id) {

this.id = id;

}

@Override

public String call() throws Exception {

return "result of TaskWithResult " + id;

}

public static void main(String[] args) throws Exception {

ExecutorService exec = Executors.newCachedThreadPool();

List> results = new ArrayList>();

for (int i = 0; i < 10; i++) {

results.add(exec.submit(new TaskWithResult(i)));

}

for (Future fs : results) {

System.out.println(fs.get());

}

exec.shutdown();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用Callable和Future接口来实现多线执行for循环并返回结果。具体实现步骤如下: 1. 定义一个实现Callable接口的任务类,重写call()方法,在该方法中编写需要执行的for循环代码,并将结果返回。 2. 创建一个ExecutorService线程池对象,调用submit()方法提交任务,返回一个Future对象。 3. 调用Future的get()方法获取执行结果。 下面是一个简单的示例代码: ``` import java.util.concurrent.*; public class MultiThreadForLoop { public static void main(String[] args) throws ExecutionException, InterruptedException { // 创建一个线程池 ExecutorService executorService = Executors.newFixedThreadPool(2); // 提交任务 Future<Integer> future1 = executorService.submit(new MyTask(1, 10)); Future<Integer> future2 = executorService.submit(new MyTask(11, 20)); // 获取执行结果 int result1 = future1.get(); int result2 = future2.get(); System.out.println("result1 = " + result1); System.out.println("result2 = " + result2); // 关闭线程池 executorService.shutdown(); } } class MyTask implements Callable<Integer> { private int start; private int end; public MyTask(int start, int end) { this.start = start; this.end = end; } @Override public Integer call() throws Exception { int sum = 0; for (int i = start; i <= end; i++) { sum += i; } return sum; } } ``` 在上面的示例中,我们创建了一个线程池,并提交了两个任务。每个任务都是一个MyTask对象,它实现了Callable接口。在MyTask的call()方法中,我们编写了一个for循环,计算出从start到end的整数之和,并将结果返回。最后,我们使用Future对象的get()方法获取执行结果,并输出到控制台。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值