• 线程池


    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;
                    }
                }
            }
        }
  • 相关阅读:
    VUE框架的初识
    cookie和session的区别及在Django中应用
    Django分页器的设置
    Django中manger/QuerySet类与mysql数据库的查询
    photoshop cc 2017使用快捷方式
    markdown基础语法
    pycharm中的flask项目如何开启debug模式
    flask连接数据库
    flask连接数据库
    pycharm中的flask项目如何开启debug模式
  • 原文地址:https://www.cnblogs.com/webglcn/p/10643445.html
Copyright © 2020-2023  润新知