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;
                    }
                }
            }
        }
  • 相关阅读:
    OpenCV 学习笔记(1-1)opecv3.41及其扩展库在VS2015下配置
    OpenCV 学习笔记(11)像素级别指针操作
    (19) 树莓派发送微信消息
    mybatis+spring配置
    spring Ioc 实践
    运用BufferedWriter把数据写入文件
    【转】跟我一起学Spring 3(4)–深入理解IoC(控制反转)和DI(依赖注入)
    [转]Spring MVC之@RequestMapping 详解
    python错误处理
    python函数
  • 原文地址:https://www.cnblogs.com/webglcn/p/10643445.html
Copyright © 2011-2022 走看看