【发布时间】:2017-01-02 01:52:15
【问题描述】:
我是使用 Java 线程池的新手。现在我有一个单元测试的用例,当一个新任务到来并且当前线程数是最大数并且队列已满时。我知道在这种情况下RejectedExecutionException 会被抛出。但是如何最好地产生这个场景,我现在能想到的是这样的:
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1);
ExecutorService ex = new ThreadPoolExecutor(2, 2, 60L, TimeUnit.MILLISECONDS, queue);
int rejected = 0;
try{
while (true){
ex.submit(() -> {
System.out.println("Queue remaining size: " + queue.remainingCapacity());
System.out.println("Thread amount in pool: " + ((ThreadPoolExecutor)ex).getPoolSize() + "\n");
});
}
}
catch (RejectedExecutionException e){
System.out.println(++rejected);
}
这是基本想法,如果方法正确,我需要使用 EasyMock 进行转换。我想知道如果使用 EasyMock 而不是继续提交任务直到线程和队列已满,是否有更好的方法。
【问题讨论】:
标签: java multithreading unit-testing