我有一种控制botMovement()机器人的方法。使用来自ArrayList的参数值/项调用它两次,如下所示:
for (BOTx1 aBot : theBotAL) { // theBotAL contains the BOTs DataType
botMovement(aBot);
} 我希望这两种方法/功能同时执行,这样一个机器人(USB机器人)就不会在另一个机器人之前移动。
我理解for循环逐元素迭代元素,因此不适合同时执行,因此尝试如下:
botMovement(theBotAL.get(0)); botMovement(theBotAL.get(1));不过,虽然延误较少,但我明白这亦会造成轻微的延误。
因此,我想知道是否有一种方法同时调用两个方法,以便botMovement是同步的。
发布于 2018-11-02 09:01:26
第一个问题是,您是从一个线程调用botMovement (以防botMovement不会在内部创建线程),因此它们不是同时运行,而是按顺序运行。
最好是创建两个线程,它们将等待锁存器,当您调用countDown()时,它们将被通知启动。
// CREAT COUNT DOWN LATCH
CountDownLatch latch = new CountDownLatch(1);
//create two threads:
Thread thread1 = new Thread(() -> {
try {
//will wait until you call countDown
latch.await();
botMovement(theBotAL.get(0))
} catch(InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
//will wait until you call countDown
latch.await();
botMovement(theBotAL.get(1))
} catch(InterruptedException e) {
e.printStackTrace();
}
});
//start the threads
thread1.start();
thread2.start();
//threads are waiting
//decrease the count, and they will be notify to call the botMovement method
latch.countDown();https://stackoverflow.com/questions/53109331
复制相似问题