博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Callable 的使用
阅读量:4486 次
发布时间:2019-06-08

本文共 1937 字,大约阅读时间需要 6 分钟。

通过实现callable的call方法可以完成线程的操作,并且返回一个需要的值

package test1;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class TaskWithResult implements Callable
{ // 实现call方法,在方法中输出两句话 public String call() throws Exception { //Thread.sleep(time); System.out.println(Thread.currentThread().getName() + "run..."); Thread.sleep(100); System.out.println(Thread.currentThread().getName() + "test..."); // 返回一个字符串 return Thread.currentThread().getName() + " has executed"; } public static void main(String[] args) throws InterruptedException, ExecutionException { // 用Executors来管理线程 ExecutorService exec = Executors.newCachedThreadPool(); // 用Future来接受返回值 List
> results = new ArrayList
>(); for(int i=0; i<=10; i++){ // 将返回值放入Future
类型的List中去 results.add(exec.submit(new TaskWithResult())); } // 得到返回值 //System.out.println(results.get(0).get()); exec.shutdown(); }}

输出结果

pool-1-thread-1run...pool-1-thread-2run...pool-1-thread-3run...pool-1-thread-4run...pool-1-thread-5run...pool-1-thread-7run...pool-1-thread-8run...pool-1-thread-9run...pool-1-thread-11run...pool-1-thread-6run...pool-1-thread-10run...pool-1-thread-2test...pool-1-thread-1test...pool-1-thread-4test...pool-1-thread-3test...pool-1-thread-9test...pool-1-thread-8test...pool-1-thread-7test...pool-1-thread-5test...pool-1-thread-10test...pool-1-thread-6test...pool-1-thread-11test...

看出来程序不是顺序运行的,而是将每一个线程分时运行。

 

可以通过Future的get()来得到返回值

pool-1-thread-1test...pool-1-thread-1 has executedpool-1-thread-3test...pool

 

 

 

转载于:https://www.cnblogs.com/xinyuyu/p/3706508.html

你可能感兴趣的文章
Spark项目之电商用户行为分析大数据平台之(七)数据调研--基本数据结构介绍...
查看>>
原来fb可以在一个工程里面输出多个swf模块
查看>>
Codeforces Round #271 (Div. 2) E. Pillars 线段树优化dp
查看>>
Codeforces Round #FF (Div. 2) D. DZY Loves Modification 优先队列
查看>>
[SPOJ705]不同的子串
查看>>
【学习】logger
查看>>
超市管理系统—运行结果及总结
查看>>
oracle存储过程语法
查看>>
将滚动条滚动到最底部
查看>>
Delphi APP 開發入門(十)REST Client 開發
查看>>
elk
查看>>
.net 模糊匹配路径
查看>>
easywechat微信分享好友、朋友圈接口-YII2
查看>>
jQuery - AJAX get()和post()方法
查看>>
用包来组织模型
查看>>
ORA-29857: 表空间中存在域索引和/或次级对象
查看>>
LeetCode58 Length of Last Word
查看>>
Python基础语法 系统学习
查看>>
推荐15款好用的JS开发工具
查看>>
ios开发之数据的持久化存储机制
查看>>