编写多线程程序一般有三种方法,Thread,Runnable,Callable.

Runnable和Callable的区别是:

(1)Callable规定的方法是call(),Runnable规定的方法是run()。其中Runnable可以提交给Thread来包装下,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。 
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值得 
(3)call方法可以抛出异常,run方法不可以 
(4)运行Callable任务可以拿到一个Future对象,c表示异步计算的结果。

Future 提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用 get 方法来获取结果,如果线程没有执行完,Future.get()方法可能会阻塞当前线程的执行;如果线程出现异常,Future.get()会throws InterruptedException或者ExecutionException;如果线程已经取消,会跑出CancellationException。取消由cancel 方法来执行。isDone确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明Future<?> 形式类型,并返回 null 作为底层任务的结果。

/**
* 通过简单的测试程序来试验Runnable、Callable通过Executor来调度的时候与Future的关系
*/
package com.hadoop.thread; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class RunnableAndCallable2Future { public static void main(String[] args) { // 创建一个执行任务的服务
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
//1.Runnable通过Future返回结果为空
//创建一个Runnable,来调度,等待任务执行完毕,取得返回结果
Future<?> runnable1 = executor.submit(new Runnable() {
@Override
public void run() {
System.out.println("runnable1 running.");
}
});
System.out.println("Runnable1:" + runnable1.get()); // 2.Callable通过Future能返回结果
//提交并执行任务,任务启动时返回了一个 Future对象,
// 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作
Future<String> future1 = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "result=task1";
}
});
// 获得任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行
System.out.println("task1: " + future1.get()); //3. 对Callable调用cancel可以对对该任务进行中断
//提交并执行任务,任务启动时返回了一个 Future对象,
// 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作
Future<String> future2 = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
try {
while (true) {
System.out.println("task2 running.");
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Interrupted task2.");
}
return "task2=false";
}
}); // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环
Thread.sleep(10);
System.out.println("task2 cancel: " + future2.cancel(true)); // 4.用Callable时抛出异常则Future什么也取不到了
// 获取第三个任务的输出,因为执行第三个任务会引起异常
// 所以下面的语句将引起异常的抛出
Future<String> future3 = executor.submit(new Callable<String>() { @Override
public String call() throws Exception {
throw new Exception("task3 throw exception!");
} });
System.out.println("task3: " + future3.get());
} catch (Exception e) {
System.out.println(e.toString());
}
// 停止任务执行服务
executor.shutdownNow();
}
}

执行结果如下:

runnable1 running.
Runnable1:null
task1: result=task1
task2 running.
task2 cancel: true
Interrupted task2.
java.util.concurrent.ExecutionException: java.lang.Exception: Bad flag value!

FutureTask则是一个RunnableFuture,即实现了Runnbale又实现了Futrue这两个接口,另外它还可以包装Runnable和Callable,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。

public class FutureTaskTest {

    /**
* @param args
*/
public static void main(String[] args) {
Callable<String> task = new Callable<String>() {
public String call() {
System.out.println("Sleep start.");
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Sleep end.");
return "time=" + System.currentTimeMillis();
}
}; //直接使用Thread的方式执行
FutureTask<String> ft = new FutureTask<String>(task);
Thread t = new Thread(ft);
t.start();
try {
System.out.println("waiting execute result");
System.out.println("result = " + ft.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //使用Executors来执行
System.out.println("=========");
FutureTask<String> ft2 = new FutureTask<String>(task);
Executors.newSingleThreadExecutor().submit(ft2);
try {
System.out.println("waiting execute result");
System.out.println("result = " + ft2.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}

执行结果如下:

waiting execute result
Sleep start.
Sleep end.
result = time=1370844662537
=========
waiting execute result
Sleep start.
Sleep end.
result = time=1370844672542

Callable,Runnable的区别及用法的更多相关文章

  1. Runnable、Callable、Future和FutureTask用法

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

  2. Runnable和Callable之间的区别

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

  3. 说一下 runnable 和 callable 有什么区别?(未完成)

    说一下 runnable 和 callable 有什么区别?(未完成)

  4. Callable,Runnable比较及用法

    http://blog.csdn.net/xtwolf008/article/details/7713580 http://www.cnblogs.com/whgw/archive/2011/09/2 ...

  5. CountDownLatch和CyclicBarrier区别及用法的demo

    javadoc里面的描述是这样的. CountDownLatch: A synchronization aid that allows one or more threads to wait unti ...

  6. Java 使用线程方式Thread和Runnable,以及Thread与Runnable的区别

    一. java中实现线程的方式有Thread和Runnable Thread: public class Thread1 extends Thread{ @Override public void r ...

  7. Callable, Runnable, Future, FutureTask

    Java并发编程之Callable, Runnable, Future, FutureTask Java中存在Callable, Runnable, Future, FutureTask这几个与线程相 ...

  8. callable与runable区别?switch char ?sql只查是否存在,sql复制表 ?反射 ? spring mvc 和spring 上下文区别?

    中化技术部  2018.4.16 1. callable 和 thread 区别 实现Callable接口的线程能返回执行结果,而Runable 不可以 . Callable 的call方法允许抛出异 ...

  9. Position属性四个值:static、fixed、absolute和relative的区别和用法

    Position属性四个值:static.fixed.absolute和relative的区别和用法 在用CSS+DIV进行布局的时候,一直对position的四个属性值relative,absolu ...

随机推荐

  1. wpf仿qq边缘自动停靠,支持多屏

    wpf完全模仿qq边缘自动隐藏功能,采用鼠标钩子获取鼠标当前状态,在通过当前鼠标的位置和点击状态来计算是否需要隐藏. 以下是实现的具体方法: 一.鼠标钩子实时获取当前鼠标的位置和点击状态 /// &l ...

  2. java中byte是什么类型,和int有什么区别

    byte字节型,int是整型,byte是8bit,int是32bit. byte可以转换为int,但int转byte可能会报错,因为精度问题,可能会超过上界.char也可转int,互转int的关系和b ...

  3. c++ 拷贝构造函数 继承

    拷贝构造函数要求把所有变量都需要做拷贝.在有继承关系情况先,子类的拷贝构造函数,需要调用父类拷贝构造函数.示例代码如下: class Base{ public: virtual ~Base(); Ba ...

  4. Python程序设计2——列表和元组

    数据结构:更好的说法是从数据角度来说,结构化数据,就是说数据并不是随便摆放的,而是有一定结构的,这种特别的结构会带来某些算法上的性能优势,比如排序.查找等. 在Python中,最基本的数据结构是序列( ...

  5. window.location和window.location.href和document.location的关系

    1,首先来区分window.location和window.location.href. window.location.href是一个字符串. 而window.location是一个对象,包含属性有 ...

  6. android studio中退出时弹出对话框

    在app中总是不小心点击了退出怎么办?当然是加个弹出的提示框了,本人新手,就加在主界面上了 @Override public boolean onKeyDown(int keyCode, KeyEve ...

  7. seleniumIDE是Firefox的录制功能使用

    selenium第二课(脚本录制seleniumIDE的使用) 转自:https://www.cnblogs.com/hustar0102/p/5906958.html 一.Selenium也具有录制 ...

  8. Linq to Objects for Java

    好几年不写博客了,人也慢慢变懒了.然而想写了却不知道写点啥,正好最近手头有点小项目就分享一下经历. 现在 java 的大环境下,基本都是围着 spring 转,加上一堆其他的库.有了架子就开始搞业务了 ...

  9. java项目中获取文件路径的几种方法

    // 第一种: 2 File f = new File(this.getClass().getResource("/").getPath()); // 结果: /Users/adm ...

  10. ubuntu - 14.04,该如何分区安装(初学者或不用它作为生成环境使用)?

    ubuntu14.04,实际上现在它的安装很简单了,全图形界面,可以选择母语,但是实际使用起来如果分区不当,会让我们付出惨痛的代价,那么我们应该怎么分区安装呢? 如果我们并不是把它作为专业的服务器,或 ...