出现高CPU占用的原因是由于ArrayBlockingQueue.poll()操作锁定了线程,并导致线程在等待队列中空转等待新元素出现。为了解决这个问题,可以使用take()方法,该方法会在队列为空时阻塞线程,直到队列中有了新的元素。
示例代码如下:
import java.util.concurrent.ArrayBlockingQueue;
public class Test {
private static final int SIZE = 10;
private static final ArrayBlockingQueue queue = new ArrayBlockingQueue<>(SIZE);
public static void main(String[] args) {
// 生产者线程
Thread producer = new Thread(() -> {
int i = 0;
while (true) {
try {
queue.put(i++);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
while (true) {
try {
int elem = queue.take();
System.out.println(elem);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
通过使用take()方法替换poll()方法,队列为空时消费者线程会阻塞而不是空转等待,从而有效降低了CPU占用。