首页 > 解决方案 > 不等待线程池上可用线程的任务

问题描述

基本上我已经实现了这个简单的代码:

public static void main( String[] args ){
    int it = 1;
    ExecutorService executorService = Executors.newFixedThreadPool(2);

    while(true){

        for(int i = 0; i < 500; i++){
            System.out.println("Exec " + it + " " + i);
            executorService.execute(new Runnable(){
                @Override
                public void run(){
                    System.out.println("entered");
                    try{
                       Thread.sleep(1000);
                    }catch ( InterruptedException e ){
                            e.printStackTrace();
                    }
               }
            });
            }
            System.out.println("Finished it "+ it++);
        }
    }

上面的代码开始向 executorService 添加无限任务,并且不等待线程可用。这意味着我们可以在迭代 N 并且仍然从迭代 1 执行任务......

我希望能够执行这些任务,但我想为它们提供服务,因为池中的线程可用,所以我不会用完资源。

谢谢你。

标签: javamultithreadingloopsexecutorservice

解决方案


推荐阅读