zoukankan      html  css  js  c++  java
  • 线程池内的线程是否需要销毁?

    结论:线程池管理的线程不用销毁,起到复用效果。使用Thread.currentThread().interrupt();好像也没有明显的效果。线程池的线程就像外包公司的员工一样,招进来了,即使没有活干也要有一个工号

    package com.example.app10;
    
    import org.springframework.stereotype.Component;
    
    import java.io.IOException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    @Component
    public class ThreadTool {
    
        private ExecutorService pool = Executors.newFixedThreadPool(10);
    
        public void saveWsRequest( ) {
            pool.execute(new ElasticsearchWsWritThread());
        }
    
        class ElasticsearchWsWritThread implements Runnable {
    
            public ElasticsearchWsWritThread( ) {
    
            }
    
            @Override
            public void run() {
                try {
    
                    System.out.println(Thread.currentThread().getName()+"--"+System.currentTimeMillis());
                    Thread.sleep(5000);
                    //Thread.currentThread().interrupt();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
    
        }
    
    
    
    
    
    }
    
    
    package com.example.app10;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    
    @Controller
    public class TestController {
    
        @Autowired
        private ThreadTool threadTool;
        @RequestMapping("test")
        public String start(){
            System.out.println();
            for(int i = 0; i<100;i++){
                threadTool.saveWsRequest();
            }
         return "test1243";
        }
    }
    
    


    通过这个动画可以推测 newFixedThreadPool如果需要的线程数超出了线程池的大小就会产生等待。但是不知道会不会产生超时。我自己写的测试已经跑了十几分中了还在执行,没有报超时。

    多线程中,调用了一个公共方法,这个方法很耗时,是否会阻塞其他线程调用这个方法?答案不会。这个public static 公共方法就像影分身一样。不会阻塞其他方法调用。

  • 相关阅读:
    理解HashSet及使用
    Java 集合类详解
    Java-泛型编程-使用通配符? extends 和 ? super
    回调函数及其用法
    log4j.properties 详解与配置步骤
    约瑟夫环
    泛型的约束与局限性
    把代码字体加大的办法
    System.arraycopy方法
    泛型数组列表与反射
  • 原文地址:https://www.cnblogs.com/mumian2/p/12377298.html
Copyright © 2011-2022 走看看