线程调度使用类: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

最新文章

  1. Java集合之ArrayList
  2. Web前端开发工程师养成计划【转载】
  3. mongo virtual
  4. IIS服务的命令行方式重启命令
  5. 9、数据库工程师要阅读的书籍 - IT软件人员书籍系列文章
  6. Orchard源码分析(2):Orchard.Web.MvcApplication类(Global)
  7. android 常用类
  8. oracle错误(ORA-01691),单个数据文件大小限制问题
  9. 封装同步的UIActionSheet
  10. [转]关于java中的 sychronized 同步方法 与 同步块的理解
  11. artDialog的几种基本使用
  12. 在asp.net中导出表格Excel数据
  13. PHP环境搭配
  14. thinkphp学习笔记4—眼花缭乱的配置
  15. Spring搭建MVC WEB项目[转]
  16. 【百度地图API】如何批量转换为百度经纬度
  17. Python使用Ctypes与C/C++ DLL文件通信过程介绍及实例分析
  18. C#利用Vini.cs操作INI文件
  19. shell脚本--php执行普通shell命令
  20. java多线程快速入门(十七)

热门文章

  1. HttpContext.Current.Session 和 Session 的区别
  2. Guava Finalizer
  3. @ZooKeeper注册中心安装(单节点)
  4. gamma函数及相关其分布
  5. RxJava RxPermissions 动态权限 简介 原理 案例 MD
  6. Eclipse版本控制Git不能Pull或者Push
  7. 数据库迁移工具Navicat Premium之OracleToMysql
  8. Android7.0新特性,及Android N适配
  9. artTemplate 简洁语法版
  10. 【Nodejs】使用http.request批量下载MP3,发现网络文件大于1000K时下载文件为0K