说说Runnable与Callable
Callable接口:
public interface Callable<V> {
V call() throws Exception;
}
Runnable接口:
public interface Runnable {
public abstract void run();
}
相同点:
- 两者都是接口;(废话)
- 两者都可用来编写多线程程序;
- 两者都需要调用Thread.start()启动线程;
不同点:
- 两者最大的不同点是:实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
- Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛;
注意点:
- Callable接口支持返回执行结果,此时需要调用FutureTask.get()方法实现,此方法会阻塞主线程直到获取‘将来’结果;当不调用此方法时,主线程不会阻塞!
Callable工作的Demo:
package com.callable.runnable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; /**
* Created on 2016/5/18.
*/
public class CallableImpl implements Callable<String> { public CallableImpl(String acceptStr) {
this.acceptStr = acceptStr;
} private String acceptStr; @Override
public String call() throws Exception {
// 任务阻塞 1 秒
Thread.sleep(1000);
return this.acceptStr + " append some chars and return it!";
} public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<String> callable = new CallableImpl("my callable test!");
FutureTask<String> task = new FutureTask<>(callable);
long beginTime = System.currentTimeMillis();
// 创建线程
new Thread(task).start();
// 调用get()阻塞主线程,反之,线程不会阻塞
String result = task.get();
long endTime = System.currentTimeMillis();
System.out.println("hello : " + result);
System.out.println("cast : " + (endTime - beginTime) / 1000 + " second!");
}
}
测试结果:
hello : my callable test! append some chars and return it!
cast : 1 second! Process finished with exit code 0
Runnable工作的Demo:
package com.callable.runnable; /**
* Created on 2016/5/18.
*/
public class RunnableImpl implements Runnable { public RunnableImpl(String acceptStr) {
this.acceptStr = acceptStr;
} private String acceptStr; @Override
public void run() {
try {
// 线程阻塞 1 秒,此时有异常产生,只能在方法内部消化,无法上抛
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 最终处理结果无法返回
System.out.println("hello : " + this.acceptStr);
} public static void main(String[] args) {
Runnable runnable = new RunnableImpl("my runable test!");
long beginTime = System.currentTimeMillis();
new Thread(runnable).start();
long endTime = System.currentTimeMillis();
System.out.println("cast : " + (endTime - beginTime) / 1000 + " second!");
}
}
测试结果:
cast : 0 second!
hello : my runable test! Process finished with exit code 0
写此篇的原因是一次面试中问到Callable与Runnable的区别,当时用的多的是Runnable,而Callable使用很少!
比较了两者后(网上查了不少),发现Callable在很多特殊的场景下还是很有用的!最后留点抄的代码,加深对Callable的认识!
package com.inte.fork; /**
* Created on 2016/4/20.
*/ import java.util.*;
import java.util.concurrent.*; import static java.util.Arrays.asList; public class Sums { static class Sum implements Callable<Long> {
private final long from;
private final long to; Sum(long from, long to) {
this.from = from;
this.to = to;
} @Override
public Long call() {
long acc = 0;
for (long i = from; i <= to; i++) {
acc = acc + i;
}
System.out.println(Thread.currentThread().getName() + " : " + acc);
return acc;
}
} public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<Long>> results = executor.invokeAll(asList(
new Sum(0, 10), new Sum(0, 1_000), new Sum(0, 1_000_000)
));
executor.shutdown(); for (Future<Long> result : results) {
System.out.println(result.get());
}
}
}
说说Runnable与Callable的更多相关文章
- Runnable、Callable、Future和FutureTask用法
http://www.cnblogs.com/dolphin0520/p/3949310.html java 1.5以前创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable ...
- Java多线程Runnable与Callable区别与拓展
我们先来分别看一下这两个接口 Runnable: // // Source code recreated from a .class file by IntelliJ IDEA // (powered ...
- Runnable和Callable之间的区别
Runnable和Callable之间的区别 1.Runnable任务执行后没有返回值:Callable任务执行后可以获得返回值 2.Runnable的方法是run(),没有返回值:Callable的 ...
- Runnable和Callable 的区别
Runnable和Callable 的区别 01.Runnable接口中只有一个run()没有返回值 没有声明异常 Callable接口中只有一个call()有返回值 有声明异常 02.Calla ...
- Runnable和Callable接口辨析
突然发现和启动一个线程有关的有三函数,run(), call(), start(),有点小乱,所以特别梳理一下 首先说一下start(),这个是最好说的,感觉start()和run()这俩名字是真的有 ...
- java 并发包runnable 与 callable
1.runnable 与 callable区别 2.避免callable执行完任务,获取返回结果时,阻塞其他子线程 下面固定线程池,设置4个,表明同时只有4个线程在执行任务,当某个线程执行完一个任务, ...
- Runnable、Callable、Executor、Future、FutureTask关系解读
在再度温习Java5的并发编程的知识点时发现,首要的就是把Runnable.Callable.Executor.Future等的关系搞明白,遂有了下述小测试程序,通过这个例子上述三者的关系就一目了然了 ...
- java Runnable、Callable、FutureTask 和线程池
一:Runnable.Callable.FutureTask简介 (1)Runnable:其中的run()方法没有返回值. ①.Runnable对象可以直接扔给Thread创建线程实例,并且创建的线程 ...
- Java并发编程之线程创建和启动(Thread、Runnable、Callable和Future)
这一系列的文章暂不涉及Java多线程开发中的底层原理以及JMM.JVM部分的解析(将另文总结),主要关注实际编码中Java并发编程的核心知识点和应知应会部分. 说在前面,Java并发编程的实质,是线程 ...
- Java中的Runnable、Callable、Future、FutureTask的区别
本文转载自:http://blog.csdn.net/bboyfeiyu/article/details/24851847 Runnable 其中Runnable应该是我们最熟悉的接口,它只有一个ru ...
随机推荐
- Tomcat 配置详解和优化
2018年01月09日 18:14:41 tianxiaojun2014 阅读数:306 转自:https://www.cnblogs.com/xbq8080/p/6417671.html htt ...
- 学习笔记:AngularJs
站点: http://www.angularjs.cn/ angularjs中文社区 http://www.jb51.net/article/60733.htm AngularJS内置指令 基本页 ...
- 1安装Linux
第二天笔记打卡. 系统安装注意:1.DATE&TIME2.Server with GUI3.分区默认4.网络开启 源代码安装:1.安装难度高2.编译环境复杂3.解决依赖关系 源代码:2.部署编 ...
- Redux使用教程
在开始之前,需要安装环境,node.js可以使用npm管理包,开发的工具webstorm可以创建相应的项目. 项目中redux是管理全局的同一个store,React-router是管理路由的,这里只 ...
- win10 下安装 neo4j(转)
1.neo4j介绍 neo4j是基于Java语言编写图形数据库.图是一组节点和连接这些节点的关系.图形数据库也被称为图形数据库管理系统或GDBMS.详细介绍可看Neo4j 教程 2.安装Java jd ...
- Echarts 饼状图自定义颜色
今天给饼状图着色问题,找了好久 终于找到了 话不多说直接上代码 $.ajax({ url: "/HuanBaoYunTai/ajax/HuanBaoYunTaiService.ashx&qu ...
- EOS踩坑记 2
[EOS踩坑记 2] 1.--contracts-console 在开发模式下,需要将 nodeos 添加此选项. 2.Debug Method The main method used to deb ...
- PTA 1067 Sort with Swap(0, i) (25 分)(思维)
传送门:点我 Given any permutation of the numbers {0, 1, 2,..., N−1}, it is easy to sort them in increasin ...
- 分布式01-Dubbo基础背景
分布式01-Dubbo基础 1-分布式基础理论 分布式系统是由一组通过网络进行通信.为了完成共同的任务而协调工作的计算机节点组成的系统.分布式系统的出现是为了用廉价的.普通的机器完成单个计算机无法完成 ...
- [leetcode]97. Interleaving String能否构成交错字符串
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Input: s1 = "aabc ...