有没有人能够为我提供一个获取RejectedExecutionException的示例呢?最好是一个真实的例子。谢谢。
有没有人能够为我提供一个获取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;
}
}
}
shutdown()
方法之后向执行器发送任务将会抛出该异常。此外,如果执行器使用有界阻塞队列且队列已满,则提交任务不会阻塞,而是会立即抛出异常。这个问题已经被问过并得到了回答: RejectedExecutionException的原因可能是什么 将任务提交给线程池会导致RejectedExecutionException
这段代码会出现错误,因为我们试图启动任务,但执行器已关闭,您可以参考上面的链接获取更多解释,答案看起来非常完整:
public class Executorz {
public static void main(String[] args) {
Executorz ex = new Executorz();
ExecutorService es = Executors.newFixedThreadPool(10);
for (int i = 0; i<100 ; i++){
System.out.println("Executed");
es.execute(ex.getNewCountin());
if (i==20)
es.shutdown();
}
}
public Countin getNewCountin(){
return new Countin();
}
public class Countin implements Runnable {
@Override
public void run() {
for (double i =0; i<1000000000 ; i++){
}
System.out.println("Done");
}
}
}