gpt4 book ai didi

java - 检查线程池是否有等待执行的任务?

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:19 25 4
gpt4 key购买 nike

这就是我试图提出解决方案的场景:

You got a parking house with 2000 free slots. It has 4 entrances. When the parking house is full, there is only allowed 50 cars to wait in each entrance.

我最终做的是创建一个包含 2000 个线程的线程池,然后用 4 个线程代表入口。他们以随机的间隔创建汽车任务(它们基本上只是调用Thread.sleep())并将它们提交到线程池。

当线程池忙于执行 2000 个任务时,就会出现问题,而新提交的任务会被放入队列中等待执行。我该如何应对在入口处等待的情况?我似乎找不到一种方法来检查线程池是否“已满”或类似的情况。或者也许我的方法是完全错误的。

最佳答案

Now how do I deal with waiting in the entrances instead? I can't seem to find a way to check if the threadpool is "full" or anything like that.

嗯。使用 Java 并发类有多种方法可以做到这一点。一种方法是使用一个大小限制为 2000 的 BlockingQueue 来表示 parking 场槽位。然后有 4 个单线程执行器服务线程池,每个线程池都有一个 50 的队列,代表 4 个入口。一旦第 51 辆车尝试在入口处排队,就会抛出 RejectedExecutionException

类似于:

final int NUM_SPACES_IN_LOT = 2000;
final int ENTRANCE_QUEUE_SIZE = 50;
final BlockingQueue<Car> parkingLot = new LinkedBlockingQueue<>(NUM_SPACES_IN_LOT);
...
ExecutorService entrance1 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(ENTRANCE_QUEUE_SIZE));
ExecutorService entrance1 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(ENTRANCE_QUEUE_SIZE));
ExecutorService entrance1 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(ENTRANCE_QUEUE_SIZE));
ExecutorService entrance1 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(ENTRANCE_QUEUE_SIZE));
...
private class ParkCar implements Runnable {
private final Car car;
public ParkCar(Car car) {
this.car = car;
}
public run() {
parkingLot.put(car);
}
}
...
Car car = new Car();
try {
entrance1.submit(new ParkCar(car));
} catch (RejectedExecutionException jee) {
// entrance is full
}
...
// remove a car from the lot, warning this is O(N)
parkingLot.remove(car);

您需要每个入口队列和每个入口线程来进行并发 parking 。如果您不希望入口已满,您可以调用 entranceX.setRejectedExecutionHandler(...) 设置处理程序,并且不希望它抛出异常。

我不喜欢这个实现的地方是,parkingLot.remove(...)O(N),但如果不自己编写的话,就没有阻塞集。

关于java - 检查线程池是否有等待执行的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41166462/

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