zoukankan      html  css  js  c++  java
  • 线程池

    ThreadPoolExecutor 核心参数 corePoolSize,  QueueCapacity(ArrayBlockingQueue的参数),  maxPoolSize

    1 If the number of threads is less than the corePoolSize, create a new Thread to run a new task.
    2 If the number of threads is equal (or greater than) the corePoolSize, put the task into the queue.
    3 If the queue is full, and the number of threads is less than the maxPoolSize, create a new thread to run tasks in.
    4 If the queue is full, and the number of threads is greater than or equal to maxPoolSize, reject the task, may throws exception.

    使用有界队列ArrayBlockingQueue,设定队列元素个数,避免OOM。 

    异步执行不阻塞 execute(xxx)

    ExecutorService executeService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
    
    executeService.execute(new MyRunner()); // execute

    异步阻塞, 设置线程名 submit(xxxx)

        public static void main(String[] args) throws Exception {
    
            Collection<Future<?>> futures = new LinkedList<Future<?>>();
            ExecutorService executeService = new ThreadPoolExecutor(3, 6, 0L, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<Runnable>(2), new CustomThreadFactory());
    
            for (int i = 0; i < 1; i++) {
                futures.add(executeService.submit(new MyRunner()));
            }
    
            for (Future<?> future : futures) {
                future.get(); // 阻塞,主线程等待线程结束
            }
    
            System.out.println("......done...........");
        }
    
    
    
        /**
         * 设置线程名
         *
         */
        private static class CustomThreadFactory implements ThreadFactory {
            private static final AtomicInteger threadNumber = new AtomicInteger(1);
    
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                String threadName = "ley's thread" + threadNumber.getAndIncrement() + " " + t.hashCode();
                t.setName(threadName);
                return t;
            }
        }
    
    
        public static class MyRunner implements Runnable {
    
            @Override
            public void run() {
    
                System.out.println("current thread==>:" + Thread.currentThread().getName());
                while (true) {
                    if (Thread.currentThread().getName().contains("ley's thread2")) {
                        int i = 1;
                        int j = 0;
                        int k = i / j;
                    }
                }
            }
        }
  • 相关阅读:
    教准备租房的同学如何避开坑!
    mvc3中controler和view之间的数据传递
    WebMail发送邮件
    mvc Razor视图语法与Aspx视图语法对比
    SQL Server sql分页查询
    WCF之一
    C++总结笔记(一)抽象、多态、继承
    Perl脚本学习经验(二)常用命令举例
    makefile学习经验(四)编译生成动态库文件(方式二)
    makefile学习经验(三)编译生成动态库文件(方式一)
  • 原文地址:https://www.cnblogs.com/webglcn/p/10643445.html
Copyright © 2011-2022 走看看