关闭静态创建的executorservice块本身已分配变量?

问题描述 投票:0回答:1

我只是想知道这段代码的工作方式的解释

假设下面有Work

 public  class Work  {
    private static ThreadPoolExecutor executorService;

    private  Work(){};

    public static void instansiate(int numberOfThread){
        executorService= (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThread);
    }

    public static void shutDown(){
        executorService.shutdown();
    }

    public static ExecutorService getExecutorService() {
        return executorService;
    }

    public static int getThreadCount(){
        return executorService.getCorePoolSize();
    }
}

并且我在类似下面的方法中的某个地方调用此类

 public static void xx() throws ExecutionException, InterruptedException {
    Work.instansiate(2);
    System.out.println("Thread count= " + Work.getThreadCount());
    ExecutorService executorService = Work.getExecutorService();
    Future<String> future1 = executorService.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "future1";
        }
    });
    String resFuture1 = future1.get();
    System.out.println(resFuture1);
    Work.shutDown();
    Future<String> future2 = executorService.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "future2";
        }
    });

    String resFuture2 = future2.get();
    System.out.println(resFuture2);

}

此代码在Work.shutDown()行之后引发异常,并说被java.util.concurrent.ThreadPoolExecutor@234bef66 [拒绝,已终止,池大小= 0,活动线程= 0 ...

我已将Work.getExecutorService分配给另一个executorService,关闭Work executorservice会如何阻止分配的一个。

java executorservice
1个回答
0
投票

实际上executorService与Work.executorService()持有相同的引用,因此关闭Work的executorservice受到影响。

© www.soinside.com 2019 - 2024. All rights reserved.