ScheduledThreadPoolExecutor 线程池调度 使用
Posted eason-d
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ScheduledThreadPoolExecutor 线程池调度 使用相关的知识,希望对你有一定的参考价值。
package other; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class TestScheduledThreadPool { public static void main(String[] args) { MyThreadFactory threadFactory = new MyThreadFactory(); //ScheduledThreadPoolExecutor // 继承 ThreadPoolExecutor 线程池 // 实现ScheduledExecutorService 线程调度 ScheduledExecutorService ses = Executors.newScheduledThreadPool(3, threadFactory); System.out.println("reday go."); TimeUnit unit = TimeUnit.SECONDS; //延时任务 ses.schedule(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName() + "delay Runnable"); } }, 1, unit); //延时任务 带返回值 ScheduledFuture<Integer> scheduledFuture = ses.schedule(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName() + "delay Callable"); return (int)(Math.random()*1000); } }, 1, unit); try { System.out.println(scheduledFuture.get()); } catch (Exception e1) { e1.printStackTrace(); } //循环执行 //以开始时间 计算 下一次任务开始时间, 如果任务执行超出循环时间,则会任务执行完后再次执行 /*ses.scheduleAtFixedRate(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName() + " scheduleAtFixedRate begin:" + DataThreadLoadUtil.convertToStr(new Date())); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " scheduleAtFixedRate end:" + DataThreadLoadUtil.convertToStr(new Date())); } }, 0, 1, unit);*/ //循环执行 //以结束时间 计算下一次执行时间 /*ses.scheduleWithFixedDelay(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName() + " scheduleWithFixedDelay begin:" + DataThreadLoadUtil.convertToStr(new Date())); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " scheduleWithFixedDelay end:" + DataThreadLoadUtil.convertToStr(new Date())); } }, 0, 5, unit);*/ /*for (int i = 0; i < 10; i++) { ses.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName() + "---------"); return (int)(Math.random()*1000); } }); }*/ System.out.println("==========end"); //ses.shutdown(); } } class MyThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { // TODO Auto-generated method stub System.out.println("ThreadFactory new Thread"); return new Thread(r); } }
以上是关于ScheduledThreadPoolExecutor 线程池调度 使用的主要内容,如果未能解决你的问题,请参考以下文章