我们知道创建线程有2种方式,一种是直接继承Thread类,另外一种就是实现Runnable接口。
public class Thread implements Runnable
Thread其实也是实现了Runnable接口。提供了可以通过new Thread(runnable).start();这种形式来完成异步任务的执行。
但是因为这种直接new的形式不利于管理、维护以及Thread的后续垃圾回收等可能导致系统性能问题,强烈不建议使用这种形式来完成异步任务。
无论何时当你看到这种形式的代码:
new Thread(runnable).start();
并且你可能最终希望获得一个更加灵活的执行策略时,请认真考虑使用Executor代替Thread。
–摘自《JAVA并发编程实践(中文)》
Runnable的接口, run方法的返回值是void:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Runable的初衷是希望将任务的执行策略和任务的业务逻辑进行解耦。Runnable是封装业务的内部逻辑。Executor框架是封装执行策略。
无论是通过Thread还是通过Runnable接口都有一个缺陷就是:在执行完任务之后无法获取执行结果。如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。所以Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。
java.util.concurrent.Callable.java
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。
那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在java.util.concurrent.ExecutorService接口中声明了若干个submit方法的重载版本:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
第一个submit方法里面的参数类型就是Callable。
暂时只需要知道Callable一般是和ExecutorService配合来使用的,具体的使用方法讲在后面讲述。
一般情况下我们使用第一个submit方法和第三个submit方法,第二个submit方法很少使用。
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
Future类位于java.util.concurrent包下,它是一个接口:
package java.util.concurrent;
public interface Future<V> {
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, has already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when {@code cancel} is called,
* this task should never run. If the task has already started,
* then the {@code mayInterruptIfRunning} parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*
* <p>After this method returns, subsequent calls to {@link #isDone} will
* always return {@code true}. Subsequent calls to {@link #isCancelled}
* will always return {@code true} if this method returned {@code true}.
*
* @param mayInterruptIfRunning {@code true} if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete
* @return {@code false} if the task could not be cancelled,
* typically because it has already completed normally;
* {@code true} otherwise
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* Returns {@code true} if this task was cancelled before it completed
* normally.
*
* @return {@code true} if this task was cancelled before it completed
*/
boolean isCancelled();
/**
* Returns {@code true} if this task completed.
*
* Completion may be due to normal termination, an exception, or
* cancellation -- in all of these cases, this method will return
* {@code true}.
*
* @return {@code true} if this task completed
*/
boolean isDone();
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
V get() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws TimeoutException if the wait timed out
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
思考运用 V get(long timeout, TimeUnit unit)
方法实现如下业务场景:
在网站启动时(3秒时间)获取后台配置的广告并展示广告,若其他原因没有取到广告或者没有配置启动广告,则展示默认广告。
因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。
FutureTask是Future接口的一个唯一实现类。
FutureTask的实现:
public class FutureTask<V> implements RunnableFuture<V>
FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
FutureTask提供了2个构造器:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
// 利用Executors提供的方法,将一个Runnable和待返回的结果封装成Callable.
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
代码:
public class AdvertisingTest {
public static void main(String[] args) {
String advertisingUrl ="【默认广告资源】";
ExecutorService executor = Executors.newFixedThreadPool(5);
AdTask task = new AdTask();
Future<String> result = executor.submit(task);
executor.shutdown();
try {
// 模拟其他业务操作,比如获取当前用户的信息等等
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
try {
advertisingUrl = result.get(4,TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("task 超时, 取消执行");
result.cancel(true);
e.printStackTrace();
}
System.out.println("获取广告的资源链接"+ advertisingUrl);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class AdTask implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("获取广告线程在进行进行");
// 模拟业务耗时
Thread.sleep(5000);
for(int i=0; i<10; i++){
System.out.println(i);
}
String advertisingUrl = "【后台配置的广告资源】";
System.out.println("获取广告线程完成");
return advertisingUrl;
}
}
执行结果:
获取广告线程在进行进行
主线程在执行任务
0
1
2
3
4
5
6
7
8
9
task 超时, 取消执行
获取广告线程完成
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
at com.abel.executorframework.AdvertisingTest.main(AdvertisingTest.java:22)
获取广告的资源链接【默认广告资源】
所有任务执行完毕
总结:
V get(long timeout, TimeUnit unit)
从get方法调用的此刻开始计时的timeout时间内获取结果。
若规定的时间内不能完成任务,我们希望取消任务的后续操作,boolean cancel(boolean mayInterruptIfRunning);
这个方法的调用只能保证一定触发cancel操作。其cancel的时机和结果没有任何保证。因为到JVM真正完成cancel的时间里,Runnable也同步在执行,状态也一直在变化。