Java并发编程:线程调度、池化与线程安全
1. 任务调度
在Java中,我们常常需要安排任务在未来的某个时间执行,甚至需要让任务按照一定的时间间隔重复执行。例如,我们可能希望每小时检查一次动物园动物的食物供应,并在必要时进行补充。
ScheduledExecutorService 是 ExecutorService 的子接口,可用于此类任务。我们可以使用 Executors 类中的工厂方法来获取 ScheduledExecutorService 的实例,示例代码如下:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService 的方法总结如下表所示:
| 方法名 | 描述 |
| — | — |
| schedule(Callable<V> callable, long delay, TimeUnit unit) | 在给定延迟后创建并执行 Callable 任务 |
| schedule(Runnable command, long delay, TimeUnit unit) | 在给定延迟后创建并执行 Runnable
超级会员免费看
订阅专栏 解锁全文
5344

被折叠的 条评论
为什么被折叠?



