gpt4 book ai didi

java - 对 CPU 影响巨大 LinkedBlockingQueue

转载 作者:行者123 更新时间:2023-12-02 07:48:48 24 4
gpt4 key购买 nike

我有一个名为 tasksLinkedBlockingQueue,但是当我调用 tasks.take() 并等待任务变得可用时, CPU 使用率为 100%。我有多个使用 tasks.take() 方法的线程(每个线程都有自己的 tasks 变量)。有谁知道为什么会发生这种情况吗?

tasks 变量的定义

private LinkedBlockingQueue<ComputerTask> tasks;
// snip
this.tasks = new LinkedBlockingQueue<ComputerTask>(100);

接受任务的代码

ComputerTask task = tasks.take();

提供新任务的代码

this.tasks.offer(task);

附注我不知道这是否是我的 Java 版本的问题,因为我还没有在任何其他计算机上测试过它。

java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04-413-11M3623)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-413, mixed mode)

最佳答案

I have a LinkedBlockingQueue called tasks, but when I call tasks.take() and wait for a task to become available, the CPU usage is 100%. I've got multiple threads using the tasks.take() method (every thread has its own tasks variable).

tasks.take(); 不应旋转,除非它使大量项目出队。如果队列为空,它将阻塞,因此我怀疑这不是 100% 负载的原因。我会确保您使用探查器或在 take() 周围添加调试语句,以查看它是否被多次调用。

要记住的一件事是,如果队列已满,tasks.offer(task) 会立即返回 false。我想知道您应该使用 tasks.put(task) ,它会阻塞而不是旋转。如果您使用 offer() 来确定在哪个任务处理程序上运行任务,那么当所有任务处理程序的队列已满时,您可能会不断循环?

如果您正在进行自己的任务管理,您可以考虑使用内置的 ExecutorService 类之一。然后,您可以提交所有任务或使用阻塞队列,ExecutorService 将处理向池中的每个线程提供其任务:

// start 10 threads handling the tasks
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// now submit tasks to the pools that will be run with the 10 threads
threadPool.submit(task);
...

在上面的示例中,ComputerTask 必须实现 Runnable

关于java - 对 CPU 影响巨大 LinkedBlockingQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10484693/

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