zoukankan      html  css  js  c++  java
  • JUC-线程池调度-ScheduledThreadPool

    线程调度使用类: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
  • 相关阅读:
    不知道是不是爬虫
    springCloud 搭建Eureka
    HttpsUtils
    java验证
    复选框值存数据库 存取问题
    Oracle VM VirtualBox 无法链接本地
    ssh 无法查询数据库
    CSS 分割线
    vue+Element 表格编辑
    数组,对象的深拷贝 与 浅拷贝
  • 原文地址:https://www.cnblogs.com/alsf/p/9142782.html
Copyright © 2011-2022 走看看