ThreadPoolExecutor Block When Queue Is Full?

前端 未结 8 1837
无人及你
无人及你 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:05

    Here is my code snippet in this case:

    public void executeBlocking( Runnable command ) {
        if ( threadPool == null ) {
            logger.error( "Thread pool '{}' not initialized.", threadPoolName );
            return;
        }
        ThreadPool threadPoolMonitor = this;
        boolean accepted = false;
        do {
            try {
                threadPool.execute( new Runnable() {
                    @Override
                    public void run() {
                        try {
                            command.run();
                        }
                        // to make sure that the monitor is freed on exit
                        finally {
                            // Notify all the threads waiting for the resource, if any.
                            synchronized ( threadPoolMonitor ) {
                                threadPoolMonitor.notifyAll();
                            }
                        }
                    }
                } );
                accepted = true;
            }
            catch ( RejectedExecutionException e ) {
                // Thread pool is full
                try {
                    // Block until one of the threads finishes its job and exits.
                    synchronized ( threadPoolMonitor ) {
                        threadPoolMonitor.wait();
                    }
                }
                catch ( InterruptedException ignored ) {
                    // return immediately
                    break;
                }
            }
        } while ( !accepted );
    }
    

    threadPool is a local instance of java.util.concurrent.ExecutorService which has been initialized already.

提交回复
热议问题