如何获得 RejectedExecutionException

Rol*_*all 4 java multithreading pool exception

任何人都可以为我提供一个获得RejectedExecutionException的示例 ,这可能是一个现实生活中的示例。提前致谢。

Gra*_*ray 5

任何人都可以为我提供一个获得 RejectedExecutionException 的示例,这可能是一个现实生活中的示例。

当然。以下代码将 2 个作业提交到线程池中,并且仅运行 1 个线程。它使用 a SynchronousQueue,这意味着作业队列中不会存储任何作业。

由于每个作业都需要一段时间才能运行,因此第二次执行会填充队列并抛出RejectedExecutionException.

// create a 1 thread pool with no buffer for the runnable jobs
ExecutorService threadPool =
    new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
        new SynchronousQueue<Runnable>());
// submit 2 jobs that take a while to run
/// this job takes the only thread
threadPool.execute(new SleepRunnable());
// this tries to put the job into the queue, throws RejectedExecutionException
threadPool.execute(new SleepRunnable());

public class SleepRunnable implements Runnable {
    public void run() {
        try {
            // this just sleeps for a while which pauses the thread
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是故意发生的,因为队列已满并且所有线程都很忙。如果你想避免这个问题,那么你应该创建一个更大的队列来在所有工作线程都忙时存储更多作业,增加处理作业的线程数量(尽管到目前为止只能增加这个数量),或者阻止将作业提交到线程池的代码。请参阅:如何实现阻塞线程池执行器?