gpt4 book ai didi

java - 如何在不使用阻塞队列的情况下将消息传递给另一个线程?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:23 27 4
gpt4 key购买 nike

我有一个非常简单的服务器(使用 kryonet)。客户端仅存储汽车的当前状态(x、y、角度等)并发送加速和转弯请求。

服务器正在接收请求并将它们添加到 ArrayBlockingQueue 中,物理线程会排出并读取和更新该队列。

当添加另一个玩家时,游戏速度几乎减慢一倍。我已经排除了很多事情(我将所有更新和包发送限制在 60Hz。)

我怀疑使用阻塞队列阻塞太多,导致速度变慢。

如何在不出现阻塞问题的情况下将客户端请求发送到物理线程?

最佳答案

I am suspecting that using a blocking queue is blocking so much that it is causing the slowdown.

你怀疑错了。以下测试程序通过 ArrayBlockingQueue 推送 100 万个整数:

public class ArrayBlockingQueuePerfTest {
int maxi = 1000000;

ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1000,
true);

Thread sender = new Thread("sender") {
public void run() {
try {
for (int i = 0; i < maxi; i++) {
queue.offer(i, 1, TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
};
Thread receiver = new Thread("receiver") {
public void run() {
try {
int count = 0;
long sum = 0;
while (count < maxi) {
sum += queue.poll(1, TimeUnit.SECONDS);
count++;
}
System.out.println("done");
System.out.println("expected sum: " + ((long) maxi) * (maxi - 1) / 2);
System.out.println("actual sum: " + sum);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
};

public ArrayBlockingQueuePerfTest() {
sender.start();
receiver.start();
}

public static void main(String[] args) {
new ArrayBlockingQueuePerfTest();
}
}

在我的笔记本电脑上,它会在几秒钟后终止。所以无论你的性能瓶颈在哪里,它都不是 ArrayBlockingQueue,它可以处理比你需要的至少高 3 个数量级的吞吐量。换句话说,即使您找到了一种完全不需要执行时间的线程通信方法,也最多只能将您的程序加速 0.1%。

把这个问题和所有其他性能问题带回家:解决现有代码中的任何性能问题的第一步是测量代码的哪一部分很慢,通常情况下,它不是在哪里一个期望。分析器极大地简化了这项任务。

关于java - 如何在不使用阻塞队列的情况下将消息传递给另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031150/

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