executor
在任务的简单应用中,是将任务对象runnable提交给Thread对象,应用简单。但是在多任务并发的时候,需要将任务与线程进程分离、管理,使用场合在大并发的环境中。需要对任务进程管理、调度安培。
executor接口
只有一个函数void execute(Runnable command)。不规定具体的实现,底层可以根据需要实例化相应方法。
ExecutorService接口
在原来的executor的基础上增加了管理功能。并且任务可以返回一个对象。 函数:
- void shutdown()关闭executor,不在接受新任务的提交
- List shutdownNow()关闭任务,有肯能关闭不了任务,原因是通过中断关闭任务,返货的是任务列表
- boolean isShutdown()任务是否调用shutdown。
- boolean isTerminated()是否非终止,在shutdown函数后面使用。
- boolean awaitTermination(long timeout,TimeUnit unit) throws InterruptedException 任务是否关闭,在给定的时间内,或者发生中断。与上一个函数相同
- Future submit(Callable task)提交一个callable任务,future是返回的任务
- Future submit(Runnable task, T result)同上
- Future<?> submit(Runnable task)提交任务,返回future,如果任务正常完成,null返回
- List<Future> invokeAll(Collection<? extends Callable> tasks)throws InterruptedException
- List<Future> invokeAll(Collection<? extends Callable> tasks,long timeout, TimeUnit unit) throws InterruptedException
- T invokeAny(Collection<? extends Callable> tasks) throws InterruptedException, ExecutionException
- T invokeAny(Collection<? extends Callable> tasks,long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException这四个函数是提交任务的集合。
scheduleexecutorservice接口
future接口
用于异步处理,将结果返回。通过get函数调用,并进入阻塞状态。用法如下:
interface ArchiveSearcher { String search(String target); }
class App {
ExecutorService executor = ...
ArchiveSearcher searcher = ...
void showSearch(final String target)
throws InterruptedException {
Future<String> future
= executor.submit(new Callable<String>() {
public String call() {
return searcher.search(target);
}});
displayOtherThings(); // do other things while searching
try {
displayText(future.get()); // use future
} catch (ExecutionException ex) { cleanup(); return; }
}
}
相关函数:
- boolean cancel(boolean mayInterruptIfRunning)中断get函数,如果完成则返回false
- boolean isCancelled()是被取消,true如果cancel返回true
- boolean isDone()是否完成,包含:异常、正常退出
- V get() throws InterruptedException, ExecutionException调用等待
- V get(long timeout,TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException 同上,只是增加时间。
callable接口
callable对象与runnable对象相同,可以提交给执行器执行,只是有一个不同call()函数有返回值,有异常。
V call() throws Exception
对象
fork/join
有对应的任务与运行器,原理将任务分解后,如果其他进程运行完毕就调用分解的任务,加快速度。
原子操作是基于硬件层面的设计,不是语言层面。
##随机数对于多线程要重新生成。