【问题标题】:How can I execute two methods at the same time to ensure there is no delay?如何同时执行两种方法以确保没有延迟?
【发布时间】:2018-11-01 21:03:52
【问题描述】:

我有一个控制 USB 机器人的方法botMovement()。它使用来自ArrayList 的参数值/项目调用两次,如下所示:

for (BOTx1 aBot : theBotAL) { // theBotAL contains the BOTs DataType
    botMovement(aBot);
} 

我希望同时执行这两种方法/功能,这样一个机器人(USB 机器人)就不会在另一个之前移动。

我了解 for 循环逐个元素地迭代,因此不适合同时执行,因此尝试了以下操作:

botMovement(theBotAL.get(0)); botMovement(theBotAL.get(1));

不过,虽然延迟较少,但我知道这也会导致轻微延迟。

因此,我想知道是否有一种方法可以同时调用这两种方法,从而使 botMovement 同步。

【问题讨论】:

  • 你真的在观察延迟吗?
  • @shmosel 一个非常小的。
  • 每个机器人“可以”由一个单独的线程控制,但是,仍然不能保证这些方法会被同时调用,即使使用信号量或有针对性的定时执行(所以它们会在指定的时间后运行)
  • @MadProgrammer 好的,谢谢。如何使用单独的线程控制每个机器人?
  • @LearningToPython 首先,您需要定义“如何”停止每个线程,直到您希望它们运行。也许从Concurrency in Java开始

标签: java multithreading simultaneous


【解决方案1】:

第一个问题是你从一个线程调用 botMovement(如果 botMovement 没有在内部创建线程),所以它们不是同时运行而是按顺序运行。

最好是两个创建 2 个线程等待闩锁,当您调用 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();

【讨论】:

  • 通常不可能通过保证来达到 OP 的要求,但这可能是最好的选择。
  • 太好了,谢谢。所以我必须为每一位创建一个新线程?
  • 这取决于您的用例,如果您没有太多的移动,那么创建新线程是可以的,但是如果您有很多移动,那么您应该重用线程,但是您有以某种方式将任务发送到线程。
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
相关资源
最近更新 更多