zoukankan      html  css  js  c++  java
  • 线程池的手写和拒绝策略

    手写线程池:

    AbortPolicy:直接抛出RejectedExecutionException异常阻止系统正常运行。

    public class MyThreadPoolDemo {
    public static void main(String[ ]args) {
    ExecutorService threadPool = new ThreadPoolExecutor(2,
    5,
    1L,
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(3),
    Executors.defaultThreadFactory(),
    new ThreadPoolExecutor.AbortPolicy());
            //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
            for(int i =1; i <= 10; i++) {
    threadPool.execute(() ->{
    System.out.println(Thread.currentThread().getName()+" 办理业务");
    });
    }
    }
    }

    运行结果见下图,抛异常,因为最大线程数5加上阻塞队列3最多可以容纳8个,超过8个就会抛异常


    CallerRunsPolicy: "调用者运行"一种调节机制,该策略即不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量。
    public class MyThreadPoolDemo {
    public static void main(String[ ]args) {
    ExecutorService threadPool = new ThreadPoolExecutor(2,
    5,
    1L,
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(3),
    Executors.defaultThreadFactory(),
    new ThreadPoolExecutor.CallerRunsPolicy());
    //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
    for(int i =1; i <= 10; i++) {
    threadPool.execute(() ->{
    System.out.println(Thread.currentThread().getName()+" 办理业务");
    });
    }
    }
    }

    运行结果见下图:


    DiscardOldestPolicy:抛弃队列中等待最近的任务,然后把当前任务加入队列中尝试再次提交当前任务
    public class MyThreadPoolDemo {
    public static void main(String[ ]args) {
    ExecutorService threadPool = new ThreadPoolExecutor(2,
    5,
    1L,
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(3),
    Executors.defaultThreadFactory(),
    new ThreadPoolExecutor.DiscardOldestPolicy());
    //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
    for(int i =1; i <= 10; i++) {
    threadPool.execute(() ->{
    System.out.println(Thread.currentThread().getName()+" 办理业务");
    });
    }
    }
    }

    运行结果见下图:


    DiscardPolicy:直接丢弃任务,不予任何处理也不抛出异常,如果允许任务丢失,这是最好的一种方案。
    public class MyThreadPoolDemo {
    public static void main(String[ ]args) {
    ExecutorService threadPool = new ThreadPoolExecutor(2,
    5,
    1L,
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(3),
    Executors.defaultThreadFactory(),
    new ThreadPoolExecutor.DiscardPolicy());
    //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
    for(int i =1; i <= 10; i++) {
    threadPool.execute(() ->{
    System.out.println(Thread.currentThread().getName()+" 办理业务");
    });
    }
    }
    }

    运行结果见下图:



  • 相关阅读:
    css3发光闪烁的效果
    移动端滚动加载数据实现
    JS生成一个简单的验证码
    百度地图在IOS中不显示
    vue开发神奇vue-devtools的安装
    gulp搭建服务
    webstorm中配置ES6语法
    centos 7 中防火墙的关闭问题
    centos命令
    Cesium加载影像
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/12168586.html
Copyright © 2011-2022 走看看