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