线程池内的线程是否需要销毁?

结论:线程池管理的线程不用销毁,起到复用效果。使用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 公共方法就像影分身一样。不会阻塞其他方法调用。

posted @ 2020-02-28 15:13  木棉貮号  阅读(3799)  评论(0编辑  收藏  举报