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<String> {

	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<Future<String>> results = new ArrayList<Future<String>>();
		for (int i = 0; i < 10; i++) {
			results.add(exec.submit(new TaskWithResult(i)));
		}
		for (Future<String> fs : results) {
			System.out.println(fs.get());
		}
		exec.shutdown();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,多线程获取返回结果的常用方法是使用`Future`和`Callable`接口。 首先,你需要创建一个实现了`Callable`接口的类,该类负责执行具体的任务,并返回结果。例如: ```java import java.util.concurrent.Callable; public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 执行具体的任务逻辑 // 返回结果 return 42; } } ``` 然后,你可以使用`ExecutorService`来提交任务并获取`Future`对象,它代表了异步计算的结果。例如: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(1); // 提交任务并获取Future对象 Future<Integer> future = executorService.submit(new MyCallable()); // 在需要结果的地方调用future.get()方法,该方法会阻塞直到任务完成并返回结果 int result = future.get(); System.out.println("结果:" + result); executorService.shutdown(); } } ``` 在上述代码中,我们使用`submit()`方法将`MyCallable`对象提交给线程池,并得到了一个`Future`对象。然后,我们通过调用`get()`方法来获取任务的执行结果。注意,`get()`方法会阻塞当前线程,直到任务完成并返回结果。 这样,你就可以通过多线程获取任务的返回结果了。当然,你也可以通过`Future`对象的其他方法来判断任务是否完成、取消任务等。具体使用方法可以参考Java官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值