可以通过调用Executors
类的static newSingleThreadExecutor()
方法获得单个线程池。
语法
ExecutorService executor = Executors.newSingleThreadExecutor();
Java
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) {