java.util.concurrent.executorservice
接口是executor
接口的子接口,并添加了功能来管理生命周期,这两个单独的任务和执行器本身。
序号 | 方法 | 描述 |
---|---|---|
1 | boolean awaittermination(long timeout, timeunit unit) |
阻止所有任务在关闭请求完成后执行,或发生超时,或当前线程中断,以先到者为准。 |
2 | <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks) |
执行给定的任务,返回持有它们的状态和结果的所有完成的列表。 |
3 | <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks, long timeout, timeunit unit) |
执行给定的任务,返回在所有完成或超时到期时持有其状态和结果的列表,以先发生者为准。 |
4 | <t> t invokeany(collection<? extends callable<t>> tasks) |
执行给定的任务,返回一个已经成功完成的结果(即不抛出异常)。 |
5 | <t> t invokeany(collection<? extends callable<t>> tasks, long timeout, timeunit unit) |
执行给定的任务,返回一个已经成功完成的结果(即,不抛出异常),如果有则在给定的超时过去之前。 |
6 | boolean isshutdown() |
如果执行程序已关闭,则返回true 。 |
7 | boolean isterminated() |
如果所有任务在关闭后完成,则返回true 。 |
8 | void shutdown() |
启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。 |
9 | list<runnable> shutdownnow() |
尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表。 |
10 | <t> future<t> submit(callable<t> task) |
提交值返回任务以执行,并返回代表任务待处理结果。 |
11 | future<?> submit(runnable task) |
提交一个可运行的任务执行,并返回一个表示该任务的future 。 |
12 | <t> future<t> submit(runnable task, t result) |
提交一个可运行的任务执行,并返回一个表示该任务的future 。 |
以下testthread
程序显示了基于线程的环境中executorservice
接口的使用。
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.timeunit;
public class testthread {
public static void main(final string[] arguments) throws interruptedexception {
executorservice executor = executors.newsinglethreadexecutor();
try {
executor.submit(new task());
system.out.println("shutdown executor");
executor.shutdown();
executor.awaittermination(5, timeunit.seconds);
}
catch (interruptedexception e) {
system.err.println("tasks interrupted");
}
finally {
if (!executor.isterminated()) {
system.err.println("cancel non-finished tasks");
}
executor.shutdownnow();
system.out.println("shutdown finished");
}
}
static class task implements runnable {
public void run() {
try {
long duration = (long) (math.random() * 20);
system.out.println("running task!");
timeunit.seconds.sleep(duration);
}
catch (interruptedexception e) {
e.printstacktrace();
}
}
}
}
执行上面代码,得到以下结果 -
shutdown executor
running task!
shutdown finished
cancel non-finished tasks
java.lang.interruptedexception: sleep interrupted
at java.lang.thread.sleep(native method)
at java.lang.thread.sleep(thread.java:302)
at java.util.concurrent.timeunit.sleep(timeunit.java:328)
at testthread$task.run(testthread.java:39)
at java.util.concurrent.executors$runnableadapter.call(executors.java:439)
at java.util.concurrent.futuretask$sync.innerrun(futuretask.java:303)
at java.util.concurrent.futuretask.run(futuretask.java:138)
at java.util.concurrent.threadpoolexecutor$worker.runtask(threadpoolexecutor.java:895)
at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:918)
at java.lang.thread.run(thread.java:662)