博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现Callable接口。带返回值的线程
阅读量:4310 次
发布时间:2019-06-06

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

callable

1.任务结束后可以提供一个返回值

2.其中的call方法可以抛出异常

3.运行callable可以拿到一个Future对象,Future对象表示异步计算的结果,他提供了检查计算是否完成的方法。

实现Callable接口

public class Main implements Callable{    int i;    @Override    public Object call() throws Exception {        String str=null;        for (i=0;i<100;i++){            str=Thread.currentThread().getName()+"--"+i;            System.out.println(str);        }        return str;    }}

测试

public class Client {    public static void main(String[] args) {        ExecutorService threadPool= Executors.newSingleThreadExecutor();        Future
future=threadPool.submit(new Main()); System.out.println("----------"); try { System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }}

线程结束后,future.get()方法会返回结果

转载于:https://www.cnblogs.com/neu-student/p/6662035.html

你可能感兴趣的文章
iOS开发系列--通知与消息机制
查看>>
16.jQuery属性操作
查看>>
sonar安装
查看>>
使用chrome开发者工具中的performance面板解决性能瓶颈
查看>>
bzoj:3392: [Usaco2005 Feb]Part Acquisition 交易
查看>>
MyBatis源码解析(一)
查看>>
JavaScript基础
查看>>
迪丽瑟斯特产网——选题报告(团队)
查看>>
linux下编译upx 3.93
查看>>
图像滤波
查看>>
猜年龄游戏
查看>>
博客园在线运行及一键转载
查看>>
zigbee
查看>>
字符串 专题
查看>>
【Maven】---Linux搭建Nexus3.X私服
查看>>
睿智计数器
查看>>
1.celery概述
查看>>
洛谷 P1057 传球游戏
查看>>
DAY-5 Linux系统用户、群组和权限
查看>>
一、MongoDB的下载、安装与部署
查看>>