Callable接口:

public interface Callable<V> {
V call() throws Exception;
}

Runnable接口:

public interface Runnable {
public abstract void run();
}

相同点:

  1. 两者都是接口;(废话)
  2. 两者都可用来编写多线程程序;
  3. 两者都需要调用Thread.start()启动线程;

不同点:

  1. 两者最大的不同点是:实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
  2. 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的更多相关文章

  1. Runnable、Callable、Future和FutureTask用法

    http://www.cnblogs.com/dolphin0520/p/3949310.html java 1.5以前创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable ...

  2. Java多线程Runnable与Callable区别与拓展

    我们先来分别看一下这两个接口 Runnable: // // Source code recreated from a .class file by IntelliJ IDEA // (powered ...

  3. Runnable和Callable之间的区别

    Runnable和Callable之间的区别 1.Runnable任务执行后没有返回值:Callable任务执行后可以获得返回值 2.Runnable的方法是run(),没有返回值:Callable的 ...

  4. Runnable和Callable 的区别

    Runnable和Callable 的区别 01.Runnable接口中只有一个run()没有返回值 没有声明异常   Callable接口中只有一个call()有返回值 有声明异常 02.Calla ...

  5. Runnable和Callable接口辨析

    突然发现和启动一个线程有关的有三函数,run(), call(), start(),有点小乱,所以特别梳理一下 首先说一下start(),这个是最好说的,感觉start()和run()这俩名字是真的有 ...

  6. java 并发包runnable 与 callable

    1.runnable 与 callable区别 2.避免callable执行完任务,获取返回结果时,阻塞其他子线程 下面固定线程池,设置4个,表明同时只有4个线程在执行任务,当某个线程执行完一个任务, ...

  7. Runnable、Callable、Executor、Future、FutureTask关系解读

    在再度温习Java5的并发编程的知识点时发现,首要的就是把Runnable.Callable.Executor.Future等的关系搞明白,遂有了下述小测试程序,通过这个例子上述三者的关系就一目了然了 ...

  8. java Runnable、Callable、FutureTask 和线程池

    一:Runnable.Callable.FutureTask简介 (1)Runnable:其中的run()方法没有返回值. ①.Runnable对象可以直接扔给Thread创建线程实例,并且创建的线程 ...

  9. Java并发编程之线程创建和启动(Thread、Runnable、Callable和Future)

    这一系列的文章暂不涉及Java多线程开发中的底层原理以及JMM.JVM部分的解析(将另文总结),主要关注实际编码中Java并发编程的核心知识点和应知应会部分. 说在前面,Java并发编程的实质,是线程 ...

  10. Java中的Runnable、Callable、Future、FutureTask的区别

    本文转载自:http://blog.csdn.net/bboyfeiyu/article/details/24851847 Runnable 其中Runnable应该是我们最熟悉的接口,它只有一个ru ...

随机推荐

  1. JavaWeb——jsp-config

    <jsp-config> 包括 <taglib> 和 <jsp-property-group> 两个子元素.其中<taglib> 元素在JSP 1.2 ...

  2. web应用 与 http协议

    一.web 应用 Web应用程序是一种可以通过Web访问的应用程序,用户只需要有浏览器即可访问应用程序,不需要再安装其他软件. 应用程序有两种模式C/S.B/S.C/S即客户端—服务端程序这类程序一般 ...

  3. uva-10602-贪心

    题意:有个编辑器,支持三种操作,摁下一个键盘上的字符,重复最后一个单词,删除最后一个字符.给N个字符串,必须先在编辑器内输入第一个字符, 问,输入完所有字符串最少需要摁下多少次键盘. 最多100个字符 ...

  4. 注解_Annotation

    ---恢复内容开始--- 一.什么是注解 注解,英文Annotation,它不是程序本身,是对程序的解释,在这里我会想到为什么不能使用注释呢,因为注解是关于程序对信息的处理的流程的一些说明,而且格式也 ...

  5. python——列表入门

    学习列表先分析一段程序: list = ['zx', 'xkd', 1997, 2018] list1=list+[1,2,3]#列表拼接 list2=[list,list1] print('嵌套的列 ...

  6. 关于six.with_metaclass(ABCMeta, object)的理解

    在学习Python过程中,看到了生成虚基类的方式, class PeopleBase(six.with_metaclass(ABCMeta, object)): @abstractmethod def ...

  7. SAP 图形页面

    话不多说,先上炫图. *&---------------------------------------------------------------------* *& Repor ...

  8. EF多字段求和(分组/不分组)

    分组多字段求和 query.GroupBy(q => new { q.Year, q.Month }) .Select(q => new { Year = q.Key.Year, Mont ...

  9. 【计算机网络】TCP的流量控制和拥塞控制

    TCP的流量控制 1. 利用滑动窗口实现流量控制 如果发送方把数据发送得过快,接收方可能会来不及接收,这就会造成数据的丢失.所谓流量控制就是让发送方的发送速率不要太快,要让接收方来得及接收. 利用滑动 ...

  10. 152. Maximum Product Subarray最大乘积子数组/是否连续

    [抄题]: Given an integer array nums, find the contiguous subarray within an array (containing at least ...