JUC-12.3-线程的调度
package com.wf.zhang.juc; import java.util.Random; import java.util.concurrent.*; /** * 三、工具类 : Executors * *** ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务。 */ public class TestScheduledThreadPool { public static void main(String[] args) throws ExecutionException, InterruptedException { 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 { //生成100以内随机数 int num = new Random().nextInt(100); System.out.println(Thread.currentThread().getName() + " " + num); return num; } }, 3, TimeUnit.SECONDS); //每三秒执行 System.out.println(result.get()); } pool.shutdown(); } }
结果
古人学问无遗力,少壮工夫老始成。
纸上得来终觉浅,绝知此事要躬行。