ThreadPoolExecutor Block When Queue Is Full?

前端 未结 8 1838
无人及你
无人及你 2020-11-29 17:42

I am trying to execute lots of tasks using a ThreadPoolExecutor. Below is a hypothetical example:

def workQueue = new ArrayBlockingQueue(3, f         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 18:22

    This is what I ended up doing:

    int NUM_THREADS = 6;
    Semaphore lock = new Semaphore(NUM_THREADS);
    ExecutorService pool = Executors.newCachedThreadPool();
    
    for (int i = 0; i < 100000; i++) {
        try {
            lock.acquire();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        pool.execute(() -> {
            try {
                // Task logic
            } finally {
                lock.release();
            }
        });
    }
    

提交回复
热议问题