JUC-线程池调度-ScheduledThreadPool
2024-08-28 14:39:59
线程调度使用类:ScheduledExecutorService
创建线程池调度类对象:
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
向线程池中添加任务的方法不是submit,而是:schedule
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
包含3个参数:
callable:线程执行的任务
delay:要延迟的时间
unit:延迟时间的单位:例如:秒:TimeUnit.SECONDS,分:TimeUnit.MINUTES。
例子:使得线程池中每个线程没隔3秒执行一次:
package com.atguigu.juc; import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class TestScheduledThreadPool { public static void main(String[] args) throws Exception {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5); for (int i = 0; i < 5; i++) {
Future<Integer> result = pool.schedule(new Callable<Integer>(){ @Override
public Integer call() throws Exception {
int num = new Random().nextInt(100);//生成随机数
System.out.println(Thread.currentThread().getName() + " : " + num);
return num;
} }, , TimeUnit.SECONDS); System.out.println(result.get());
}
pool.shutdown();
}
}
执行结果:
pool-1-thread-1 : 57
57
pool-1-thread-1 : 55
55
pool-1-thread-2 : 45
45
pool-1-thread-1 : 50
50
pool-1-thread-3 : 88
88
最新文章
- Java集合之ArrayList
- Web前端开发工程师养成计划【转载】
- mongo virtual
- IIS服务的命令行方式重启命令
- 9、数据库工程师要阅读的书籍 - IT软件人员书籍系列文章
- Orchard源码分析(2):Orchard.Web.MvcApplication类(Global)
- android 常用类
- oracle错误(ORA-01691),单个数据文件大小限制问题
- 封装同步的UIActionSheet
- [转]关于java中的 sychronized 同步方法 与 同步块的理解
- artDialog的几种基本使用
- 在asp.net中导出表格Excel数据
- PHP环境搭配
- thinkphp学习笔记4—眼花缭乱的配置
- Spring搭建MVC WEB项目[转]
- 【百度地图API】如何批量转换为百度经纬度
- Python使用Ctypes与C/C++ DLL文件通信过程介绍及实例分析
- C#利用Vini.cs操作INI文件
- shell脚本--php执行普通shell命令
- java多线程快速入门(十七)
热门文章
- HttpContext.Current.Session 和 Session 的区别
- Guava Finalizer
- @ZooKeeper注册中心安装(单节点)
- gamma函数及相关其分布
- RxJava RxPermissions 动态权限 简介 原理 案例 MD
- Eclipse版本控制Git不能Pull或者Push
- 数据库迁移工具Navicat Premium之OracleToMysql
- Android7.0新特性,及Android N适配
- artTemplate 简洁语法版
- 【Nodejs】使用http.request批量下载MP3,发现网络文件大于1000K时下载文件为0K