Java之Callable 和 Future实现线程等待

来源:互联网 发布:海口seo 编辑:程序博客网 时间:2024/04/30 19:54
1、Callable:
public interface Callable<V>

返回结果并且可能抛出异常的任务。实现者定义了一个不带任何参数的叫做 call 的方法。

Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。

Executors 类包含一些从其他普通形式转换成 Callable 类的实用方法。

call

V call()       throws Exception
计算结果,如果无法计算结果,则抛出一个异常。 

返回:
计算的结果
抛出:
Exception - 如果无法计算结果
2、Future:
public interface Future<V>

Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用 get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明 Future<?> 形式类型、并返回 null 作为底层任务的结果。

get

V get()      throws InterruptedException,             ExecutionException
如有必要,等待计算完成,然后获取其结果。 

返回:
计算的结果
抛出:
CancellationException - 如果计算被取消
ExecutionException - 如果计算抛出异常
InterruptedException - 如果当前的线程在等待时被中断
3、相关实例:
<pre name="code" class="java">public class TestFutureTask {public static void main(String[] args) throws InterruptedException, ExecutionException {final ExecutorService exec = Executors.newFixedThreadPool(5);Callable<String> call = new Callable<String>() {public String call() throws Exception {Thread.sleep(1000 * 3);// 休眠指定的时间,此处表示该操作比较耗时return "Other less important but longtime things.";}};Future<String> task = exec.submit(call);//Thread.sleep(1000 * 3);System.out.println("Let's do important things.");//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞boolean isDone = task.isDone();while(!isDone){isDone = task.isDone();}String obj = task.get();System.out.println(obj);// 关闭线程池exec.shutdown();}}


输出结果:
Let's do important things.Other less important but longtime things.转载:http://www.itzhai.com/callable-and-future-realization-of-the-thread-waiting-for.html
其他
public class TestFutureTask2 {public static void main(String[] args) throws InterruptedException, ExecutionException {final ExecutorService exec = Executors.newFixedThreadPool(5);Runnable runnable = new Runnable() {@Overridepublic void run() {try {Thread.sleep(1000 * 2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 休眠指定的时间,此处表示该操作比较耗时}};Future<String> task = exec.submit(runnable, "aa");System.out.println("Let's do important things.");//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞boolean isDone = task.isDone();while(!isDone){//Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds,Thread.sleep(500);isDone = task.isDone();}String obj = task.get();System.out.println(obj);//输出aa,即上面submit方法传入的参数// 关闭线程池exec.shutdown();}}
public class TestFutureTask3 {public static void main(String[] args) throws InterruptedException, ExecutionException {final ExecutorService exec = Executors.newFixedThreadPool(5);Runnable runnable = new Runnable() {@Overridepublic void run() {try {Thread.sleep(1000 * 2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 休眠指定的时间,此处表示该操作比较耗时}};Future<?> task = exec.submit(runnable);System.out.println("Let's do important things.");// 不重要的事情//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞boolean isDone = task.isDone();while(!isDone){//Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds,Thread.sleep(500);isDone = task.isDone();}String obj = (String) task.get();System.out.println(obj);//输出null// 关闭线程池exec.shutdown();}}