1. Runnable和Callable
Java多线程有两个重要的接口,Runnable和Callable,分别提供了一个call方法和一个run方法
-
相同点
- 两者都是接口
- 两者都可以用来编写多线程程序
- 两者都可以调用Thread.start()来启动线程
-
不同点
- 两个最大的不同点就是:实现Callable接口的线程能够返回结果;而实现Runnable接口的线程不能返回结果
- Callable接口的call()方法允许抛出异常;而Runnable接口的run方法的异常只能在内部消化,不能继续上抛。
- Runnable可以作为Thread构造器的参数,通过开启新的线程来执行,也可以通过线程池来执行;而Callable只能通过线程池来执行。
2. Future和FutureTask
FutureTask可以用于闭锁,它实现了Future接口,表示一种可抽象的可产成结果的计算。
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取结果,该方法会阻塞直到任务返回结果。
Future源码:
public interface Future<V> {
/*
*功能:试图取消此任务的执行
* 如果取消成功则返回true,否则返回false
*参数mayInterruptIfRunnable表示是否取消正在执行却没有执行完毕的任务,
*如果设置为true表示则可以取消正在执行的任务,如果任务已经完成,无论设置为ture还是false,此方法肯定返回false,即如果取消已经完成的任务肯定返回false
* 如果任务正在执行。如果设置为true,则返回true,若设置为false,则返回false
* 如果任务还没有执行,无论设置为true还是false,肯定返回true
*/
boolean cancel(boolean mayInterruptIfRunning);
//表示任务是否被取消成功,如果在任务被正常完成前被取消成功,则返回true
boolean isCancelled();
//表示任务是否已经被完成,如果完成则返回true
boolean isDone();
//用来获取执行的结果,这个方法或产生阻塞,会一直等待任务执行完毕才返回
V get() throws InterruptedException, ExecutionException;
/*
*功能:用来获取执行结果,如果在指定时间内还没有返回结果,则直接返回null
*他提供了三种功能功能:1.判断任务是否完成2.能够中断任务3能够获取任务的执行结果
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask有两个构造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
测试实例:FutureTask和Callable获取结果
/**
* 测试Callable
*
* @author qiang
*
*/
public class TestCallable implements Callable<String> {
private String arg;
public TestCallable(String arg) {
this.arg = arg;
}
public String call() throws Exception {
// 线程阻塞1秒,会返回这个异常
Thread.sleep(1000);
return this.arg + "append some chars and return it!";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<String> callable = new TestCallable("world");
Future<String> futuretask = new FutureTask<>(callable);
Long beginTime = System.currentTimeMillis();
// 创键线程
new Thread((Runnable) futuretask).start();// Thread只接受Runnable类型的参数
// get方法会阻塞线程,反之返回结果
String result = futuretask.get();
long endTime = System.currentTimeMillis();
System.out.println("hello " + result);
System.out.println("cast :" + (endTime - beginTime) / 1000 + "second");
}
}
测试结果:
hello worldappend some chars and return it!
cast :1second
作者:Alphathur
来源:CSDN
原文:https://blog.csdn.net/mryang125/article/details/81878168
版权声明:本文为博主原创文章,转载请附上博文链接!