可以通过调用executors
类的static newsinglethreadexecutor()
方法获得单个线程池。
语法
executorservice executor = executors.newsinglethreadexecutor();
newsinglethreadexecutor()
方法创建一次执行单个任务的执行程序。
以下testthread
程序显示了基于线程的环境中newsinglethreadexecutor()
方法的使用。
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)