调度线程池

来源:互联网 发布:中国保险保险网络大学 编辑:程序博客网 时间:2024/06/05 04:04
package executor;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;/** *  缓存性线程池 * @author muyouGou. * */public class Executor {public static void main(String[] args) throws InterruptedException, ExecutionException {ScheduledExecutorService newCachedThreadPool = Executors.newScheduledThreadPool(3);List <Future<String>> resulteList = new ArrayList<Future<String>>();//模拟线程池高峰期往,线程池里面添加for(int i=1;i<=100;i++) {//Future<String> submit = newCachedThreadPool.submit(new workTask(i));//resulteList.add(submit);ScheduledFuture<String>schedule = newCachedThreadPool.schedule(new workTask(i), 1000, TimeUnit.MICROSECONDS);resulteList.add(schedule);}for(Future<String> future : resulteList) {// 判断线程是否执行完成 ,isDone是完成!没有完成就返回一直到完成while(!future.isDone());System.out.println(future.get());}// 线程总共执行5秒钟Thread.sleep(5000);// 在实际业务中是不需要关闭线程池的,因为线程池是随着系统启动。随着系统停止而停止// 期间一直在为系统运行newCachedThreadPool.shutdown();}// 此处必须添加static 因为在main方法里是一个static的方法,所以调用的方法也必须是一个static的方法 public static class workTask implements Callable<String>{private int code;public workTask(int code) {this.code = code;}@Overridepublic String call() throws Exception {// 实际的业务逻辑System.err.println("thread name:"+Thread.currentThread().getName());return Thread.currentThread().getName()+"is finished!!";}}}
原创粉丝点击