- Java 并发教程
- 并发 - 主页
- 并发 - 概述
- 并发 - 环境设置
- 并发 - 主要操作
- 线程间通信
- 并发 - 同步
- 并发 - 死锁
- 实用程序类示例
- 并发 - ThreadLocal
- 并发 - ThreadLocalRandom
- 锁示例
- 并发 - 锁
- 并发 - 读写锁
- 并发 - 条件
- 原子变量示例
- 并发 - AtomicInteger
- 并发 - AtomicLong
- 并发 - AtomicBoolean
- 并发 - AtomicReference
- 并发 - AtomicIntegerArray
- 并发 - AtomicLongArray
- 并发 - AtomicReferenceArray
- 执行器示例
- 并发 - 执行器
- 并发 - ExecutorService
- ScheduledExecutorService
- 线程池示例
- 并发 - newFixedThreadPool
- 并发 - newCachedThreadPool
- newScheduledThreadPool
- newSingleThreadExecutor
- 并发 - ThreadPoolExecutor
- ScheduledThreadPoolExecutor
- 高级示例
- 并发 - Future 和 Callable
- 并发 - Fork-Join 框架
- 并发集合
- 并发 - BlockingQueue
- 并发 - ConcurrentMap
- ConcurrentNavigableMap
- 并发有用资源
- 并发 - 快速指南
- 并发 - 有用资源
- 并发 - 讨论
newSingleThreadExecutor 方法
可以通过调用 Executors 类中 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)
广告