zoukankan      html  css  js  c++  java
  • 线程池的工作过程示例

    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class DiscardPolicyDemo {  
    
        private static final int corePoolSize = 3;  
        private static final int maximumPoolSize = 6;  
        private static final int QueueCAPACITY = 10;  
    
        public static void main(String[] args) throws Exception {  
    
            // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE),"线程池"的阻塞队列容量为1(CAPACITY)。  
            ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QueueCAPACITY),new rejectedImpl());
    
    
    
            // 设置线程池的拒绝策略为"丢弃"  
    
            // 新建10个任务,并将它们添加到线程池中。  
            for (int i = 0; i < 20; i++) {  
                Runnable myrun = new MyRunnable("task-"+i);  
                pool.execute(myrun);  
                
            }  
            // 关闭线程池  
            pool.shutdown();  
        }  
    }
    
    class rejectedImpl implements  RejectedExecutionHandler{
    
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
             System.out.println(String.format("Task %s rejected.", r.hashCode()));
            
        }
        
    }
    class MyRunnable implements Runnable {
        private String name;
    
        public MyRunnable(String name) {
            this.name = name;
        }
    
        @Override
        public void run() {
            try {
                System.out.println(this.name + " is running.");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    运行结果:

    task-2 is running.
    task-0 is running.
    task-1 is running.
    task-13 is running.
    task-14 is running.
    task-15 is running.
    Task 460141958 rejected.
    Task 312714112 rejected.
    Task 692404036 rejected.
    Task 1554874502 rejected.
    task-3 is running.
    task-5 is running.
    task-4 is running.
    task-6 is running.
    task-7 is running.
    task-8 is running.
    task-9 is running.
    task-12 is running.
    task-11 is running.
    task-10 is running.

    Java自带的线程池ThreadPoolExecutor详细介绍说明和实例应用 
    http://fulong258.blog.163.com/blog/static/17895044201082951820935

  • 相关阅读:
    JavaScript你所不知道的困惑(3)
    Android的代码都得自己一个个敲一遍吗?
    现代化农业在美国的兴起与发展
    高内聚与低耦合实现小记
    iOS 载入图片选择imageNamed 方法还是 imageWithContentsOfFile?
    swift笔记——环境搭建及Hello,Swift!
    HDU 4832(DP+计数问题)
    [TJOI2019]甲苯先生的线段树
    2019-8-31-C#-如何写-DEBUG-输出
    2019-8-31-C#-如何写-DEBUG-输出
  • 原文地址:https://www.cnblogs.com/stevenlii/p/8883091.html
Copyright © 2011-2022 走看看