我在处理一个更复杂的版本(包含车辆在X和Y方向上移动)
我制作了这个示例来获取更好的实现方法的想法。
- 我有一辆车以速度 (24.5872 米/秒) 在X方向移动
- 我通过每100毫秒增加X值来模拟此过程,使用执行器(以保持其X位置更准确和实时)
- 每秒后,我发送一条消息到另一个进程,其中包括我刚刚覆盖的线的xMin和xMax值
- 另一个进程将用JMS消息做出响应(通常立即),如果之前的X区域中有“坑洼”,则会告诉我停止(使用消息回调msg到链接阻塞队列)。
我的问题与“通常立即”部分有关。如果我没有及时获得响应,我认为它会破坏整个算法的计时。有什么更好的方法来处理这种情况吗?
以下是我尝试做的一些基本代码:
public class Mover implements MessageHandler {
private static final long CAR_UPDATE_RATE_IN_MS = 100;
private static double currX = 0;
private static double CONSTANT_SPEED_IN_MPS = 24.5872; // 55 mph
private static double increment = CONSTANT_SPEED_IN_MPS / (1000 / CAR_UPDATE_RATE_IN_MS);
static LinkedBlockingQueue<BaseMessage> messageQueue = new LinkedBlockingQueue<BaseMessage>(); // ms
private static int incrementor = 0;
public static void main(String[] args) {
startMoverExecutor();
}
private static void startMoverExecutor() {
ScheduledExecutorService mover = Executors.newSingleThreadScheduledExecutor();
mover.scheduleAtFixedRate((new Runnable() {
@Override
public void run() {
currX = incrementor * increment;
if (incrementor % (1000 / CAR_UPDATE_RATE_IN_MS) == 0) {
System.out.println(currX);
sendMessage(currX - CONSTANT_SPEED_IN_MPS, currX);
// do something
try {
messageQueue.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
incrementor++;
}
}), 0, CAR_UPDATE_RATE_IN_MS, TimeUnit.MILLISECONDS);
}
@Override
public void handleMessage(BaseMessage msg) {
messageQueue.add(msg);
}
protected static void sendMessage(double firstX, double secondX) {
// sendMessage here
}
}
currX = incrementor * increment;
修改为currX += increment;
并将其初始化为currX = -increment;
只需改变一个符号,你就能提高代码的运行速度。 - Justin Peel