线程池



    /**
     * 当网络和代码耗时高, 线程池再多, 一样很快耗尽线程池;
     * 网络和代码耗时稳定, 适度增加线程池数量可提高单位时间内任务处理量;
     */
    private static ExecutorService executorTask = new ThreadPoolExecutor(
            1,
            1,
            100L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(2),
            new ThreadPoolExecutor.CallerRunsPolicy());


    public static void main(String[] args) throws InterruptedException {

        Callable callable = () -> {
            Thread.sleep(2000L);
            String tname = Thread.currentThread().getName();
            System.out.println(tname);

            return tname;
        };


        ArrayList> callables = new ArrayList<>();


        for (int i = 0; i < 10; i++) {
            callables.add(callable);
        }

        executorTask.invokeAll(callables);

        executorTask.shutdown();
    }


       /*

      AbstractExecutorService


    public  List> invokeAll(Collection> tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();
        ArrayList> futures = new ArrayList>(tasks.size());
        boolean done = false;
        try {

          //在main线程循环任务队列
          // CallerRunsPolicy卡住了, 循环任务队列也会被卡主, 都是在main线程执行
         
            for (Callable t : tasks) {
                RunnableFuture f = newTaskFor(t);
                futures.add(f);
                execute(f);
            }
            for (int i = 0, size = futures.size(); i < size; i++) {
                Future f = futures.get(i);
                if (!f.isDone()) {
                    try {
                        f.get();
                    } catch (CancellationException ignore) {
                    } catch (ExecutionException ignore) {
                    }
                }
            }
            done = true;
            return futures;
        } finally {
            if (!done)
                for (int i = 0, size = futures.size(); i < size; i++)
                    futures.get(i).cancel(true);
        }
    }
    
    main线程中循环任务队列
    把任务提交给子线程或任务队列,如果队列满了, 或者没有子线程接收任务, 
    则走拒绝策略, CallerRunsPolicy 在main线程执行子任务, 因为会卡住main线程循环任务队列。
    
    ThreadPoolExecutor

      public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();

       int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {


        if (addWorker(command, true)) //  子线程中执行任务
            return;
        c = ctl.get();
    }
        if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command); // main线程中执行任务

        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
        else if (!addWorker(command, false))
                reject(command);
   }



     */


你可能感兴趣的:(线程池)