6.5.4 java预定义线程池ScheduledThreadPoolExecutor 理解、使用示例

目录

两个构造方法

有两种类型 

构造理解

适用场景

周期线程池执行的常用方法

使用demo1:newSingleThreadScheduledExecutor的顺序执行

schedule:延时3秒执行

scheduleAtFixedRate:固定时间间隔执行任务

scheduleWithFixedDelay:然后执行完任务后,延迟3秒再周期执行当前任务


如果不了解线程池的各个参数的含义,可以查看此文章线程池的优点、以及各个参数的意义、使用示例

两个构造方法

 一个多了一个线程工厂的参数,能够对参数名等进行设置

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool (1);
        ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool( 1,new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newFixedThreadPool,你来打我呀");
                return thread;
            }
        });
        ScheduledExecutorService executorService3 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService executorService4 = Executors.newSingleThreadScheduledExecutor (new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newFixedThreadPool,你来打我呀");
                return thread;
            }
        });
    }
}

有两种类型 

ScheduledThreadPoolExecutor:包含多个线程的

SingleThreadScheduledExecutor:只包含一个线程的

构造理解

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. corePoolSize=0;maximumPoolSize=Integer.MAX_VALUE,最大会创建Integer.MAX_VALUE线程执行任务
  2. 等待时间默认是60秒,意味着空闲线程等待60无任务就会终止
  3. 使用CachedThreadPool无界阻塞队列,会不断创建线程

适用场景

ScheduledThreadPoolExecutor:包含多个线程的执行的周期任务,同时要限制后台线程的数量

SingleThreadScheduledExecutor:只包含一个线程的,要保证线程顺序地执行任务:上一个任务执行完了,才执行下一个任务

周期线程池执行的常用方法

public ScheduledFuture<?> schedule(

Runnable command,

long delay,

TimeUnit unit)

执行一次,延迟delay时间单位

public <V> ScheduledFuture<V> schedule(

Callable<V> callable,

long delay,

TimeUnit unit);

执行一次有返回值的任务,

延迟delay时间单位

public ScheduledFuture<?> scheduleAtFixedRate(

Runnable command,

long initialDelay,    

long period,

TimeUnit unit)

固定时间间隔执行,首次在initialDelay时间单位后执行

然后每隔period时间单位执行一次

任务执行的时间不能超过时间间隔period(不会报错)

public ScheduledFuture<?> scheduleWithFixedDelay(

Runnable command,

long initialDelay, 

long delay,

TimeUnit unit);

固定延时间隔执行,首次在initialDelay时间单位后执行

然后每隔period时间单位执行一次

每次任务完成之后都延时一个固定时间,即完成一个任务,等待delay秒

使用demo1:newSingleThreadScheduledExecutor的顺序执行

public class Test {
    static class Customer extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "--开始执行");
            try {
                //模拟任务执行4s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--执行完成");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool (2);
        ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool( 2,new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newScheduledThreadPool,你来打我呀");
                return thread;
            }
        });
        ScheduledExecutorService executorService3 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService executorService4 = Executors.newSingleThreadScheduledExecutor (new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newSingleThreadScheduledExecutor,你来打我呀");
                return thread;
            }
        });

        //执行普通没有返回值的任务,这两个任务会按照顺序执行
        System.out.println("newSingleThreadScheduledExecutor执行普通没有返回值的任务," +
                "这两个任务会按照顺序执行,前一个任务完成,后一个任务才能开始");
        for (int i = 0; i < 3; i++) {
            executorService3.execute(new Customer());
        }

//        executorService1.execute(new Customer());
//        //执行有返回值的任务
//        Future submit = executorService1.submit(new Home(1, 10));
//        System.out.println("get()方法会阻塞,直到拿到结果"+submit.get());
    }
}

结果:上一个线程执行完成之后,下一个线程才能继续执行

newSingleThreadScheduledExecutor执行普通没有返回值的任务,这两个任务会按照顺序执行,前一个任务完成,后一个任务才能开始
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成

schedule:延时3秒执行

public class Test {
    static class Customer extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "--开始执行");
            try {
                //模拟任务执行4s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--执行完成");
        }
    }
    static class Home implements Callable {
        int start;
        int end;

        public Home(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for (int i = start; i <=end; i++) {
                sum+=i;
            }
            return sum;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool (2);
        ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool( 2,new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newScheduledThreadPool,你来打我呀");
                return thread;
            }
        });
        ScheduledExecutorService executorService3 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService executorService4 = Executors.newSingleThreadScheduledExecutor (new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newSingleThreadScheduledExecutor,你来打我呀");
                return thread;
            }
        });

            System.out.println("延时3秒之后再运行");
            executorService3.schedule(new Customer(),3,TimeUnit.SECONDS);
            System.out.println("延时3秒之后再运行有返回任务");
        ScheduledFuture schedule = executorService3.schedule(new Home(1, 10), 3, TimeUnit.SECONDS);

        System.out.println("get()方法会阻塞,直到拿到结果"+schedule.get());
    }
}

结果:

延时3秒之后再运行
延时3秒之后再运行有返回任务
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
get()方法会阻塞,直到拿到结果55

scheduleAtFixedRate:固定时间间隔执行任务

public class Test {
    static class Customer extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "--开始执行");
            try {
                //模拟任务执行1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--执行完成");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool (2);
        ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool( 2,new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newScheduledThreadPool,你来打我呀");
                return thread;
            }
        });
        ScheduledExecutorService executorService3 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService executorService4 = Executors.newSingleThreadScheduledExecutor (new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newSingleThreadScheduledExecutor,你来打我呀");
                return thread;
            }
        });

        System.out.println("1秒之后首次运行,然后每隔3秒运行一次");
        executorService3.scheduleAtFixedRate(new Customer(),1,3,TimeUnit.SECONDS);
    }
}

结果:

1秒之后首次运行,然后每隔3秒运行一次
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
pool-2-thread-1--开始执行
。。。。。。

scheduleWithFixedDelay然后执行完任务后,延迟3秒再周期执行当前任务

public class Test {
    static class Customer extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "--开始执行");
            try {
                //模拟任务执行4s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--执行完成");
        }
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool(2);
        ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool(2, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newScheduledThreadPool,你来打我呀");
                return thread;
            }
        });
        ScheduledExecutorService executorService3 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService executorService4 = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newSingleThreadScheduledExecutor,你来打我呀");
                return thread;
            }
        });
        System.out.println("1秒之后首次运行,然后执行完任务后,延迟3秒再周期执行当前任务");
        executorService3.scheduleWithFixedDelay(new Customer(), 1, 3, TimeUnit.SECONDS);
    }
}

结果

1秒之后首次运行,然后执行完任务后,延迟3秒再周期执行当前任务
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
pool-2-thread-1--开始执行
pool-2-thread-1--执行完成
。。。。。。

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值