ThreadPoolExecutor 饱和策略部分的错误 #802
Closed
Comments
|
JavaGuide 仓库里面初期部分博文是参考 CSDN 的。。。属于历史原因~ 我们先看官方注释:
我的理解:当线程队列满时,直接在调用 execute 方法的调用线程中运行被拒绝的任务。 至于你贴的博文所说的「喜欢增加队列容量」,这句话有问题,因为它本身没有任何增加队列的源码,不信你看源码: public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}源码很简单,就是当触发拒绝策略时,直接在调用线程上下文运行被拒绝的任务 static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1), new ThreadPoolExecutor.CallerRunsPolicy());
public static void main(String[] args) throws InterruptedException {
threadPoolExecutor.submit((Runnable) () -> {
while (true) {
try {
System.out.println("第一个线程上下文" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {
}
}
});
TimeUnit.SECONDS.sleep(2);
System.out.println("第一个任务执行中,当前线程池里正在跑的线程数/最大线程数/队列中的线程数:" + threadPoolExecutor.getActiveCount() + "/" + threadPoolExecutor.getMaximumPoolSize() + "/" + threadPoolExecutor.getQueue().size());
TimeUnit.SECONDS.sleep(2);
threadPoolExecutor.submit((Runnable) () -> {
while (true) {
try {
// 第一个问题:为什么这行不会打印?
System.out.println("第二个线程上下文" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("第二个任务执行中:当前线程池里正在跑的线程数/最大线程数/队列中的线程数:" + threadPoolExecutor.getActiveCount() + "/" + threadPoolExecutor.getMaximumPoolSize() + "/" + threadPoolExecutor.getQueue().size());
TimeUnit.SECONDS.sleep(2);
threadPoolExecutor.submit((Runnable) () -> {
while (true) {
try {
System.out.println("第三个线程上下文" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {
}
}
});
// 第二个问题:为什么这行不会打印?
System.out.println("第三个任务执行中:当前线程池里正在跑的线程数/最大线程数/队列中的线程数:" + threadPoolExecutor.getActiveCount() + "/" + threadPoolExecutor.getMaximumPoolSize() + "/" + threadPoolExecutor.getQueue().size());
} |
Merged
我明白 CallerRunsPolicy 的作用,但是文中所说的 CallerRunsPolicy 可以提供可伸缩队列,让我觉得CallerRunsPolicy 改变了队列的容量。 |
|
文章毕竟是作者根据个人理解和能力写的,有错误笔误误导在所难免。代码这东西还是得习惯自己看源码和注释。如果有其它困惑记得提 issue,一起探讨 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
有一个疑问
我看了 ThreadPoolExecutor 的构造函数源码并没发现当最大池被填满时, ThreadPoolExecutor.CallerRunsPolicy 可以提供可伸缩队列。
然后搜索相关问题发现以下链接中
ThreadPoolExecutor 饱和策略部分完全一样,错误部分已加粗。https://snailclimb.gitee.io/javaguide/#/docs/java/Multithread/JavaConcurrencyAdvancedCommonInterviewQuestions
http://www.mianshigee.com/question/10150vgo
https://blog.csdn.net/qq_23145857/article/details/105366265
https://blog.csdn.net/agonie201218/article/details/106187740
https://www.cnblogs.com/1994jinnan/p/12331591.html
https://www.lagou.com/lgeduarticle/72192.html
https://www.cnblogs.com/ustc-anmin/p/11753277.html
The text was updated successfully, but these errors were encountered: