gpt4 book ai didi

java - 我怎样才能得到一个 RejectedExecutionException

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:49:25 26 4
gpt4 key购买 nike

谁能给我提供一个获得 RejectedExecutionException 的例子可能是一个现实生活中的例子。提前致谢。

最佳答案

Anybody able to provide me with an example of getting a RejectedExecutionException Possibly a real life example.

当然。以下代码将 2 个作业提交到一个线程池中,只有 1 个线程在运行。它使用 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;
}
}
}

关于java - 我怎样才能得到一个 RejectedExecutionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17837410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com