如何创建一个ThreadPoolExecutor,根据需要创建线程并在适用时将
发布时间:2020-12-15 02:19:07 所属栏目:Java 来源:网络整理
导读:我的用例: 为线程池设置最小大
我的用例:
>为线程池设置最小大小“N”,这意味着在Executor启动后“N”个线程始终可用. 我相信HttpClient后面的池管理器可以进行类似的设置.我正在尝试使用ThreadPoolExecutor实现它但无法找到方法.可能吗? 这是一个测试的例子. public class ExecutorExample { public static void main(String[] args) throws InterruptedException { int minPoolSize = 2; int maxPoolSize = 10; int ttlMillis = 100; ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize,maxPoolSize,// surprisingly this is not obeyed. ttlMillis,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize()); startupExecutor.execute(new MyRunnable(i)); } for (int i = 0; i < 20; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize()); } } } class MyRunnable implements Runnable { int n; public MyRunnable(int n) { this.n = n; } @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + ":" + n); } catch (InterruptedException e) { e.printStackTrace(); } } } 解决方法
这个怎么样:
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue); ThreadPoolExecutor 编辑:通常我使用的队列是有界阻塞队列. BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(queueCapacity,true); EDIT2:最大池大小仅在队列满时启动.由于您使用的是无界队列,因此线程数不会高于2. Se链接如下. rules-of-a-threadpoolexecutor-pool-size 放大小1,你会看到差异. new LinkedBlockingQueue<>(1)); 编辑3:在您的示例中,使用startupExecutor.getPoolSize()更改startupExecutor.getCorePoolSize(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |