简体   繁体   English

Scala中的未来和无限循环

[英]Future and infinite loop in Scala

I want to execute 2 independent infinite loops in scala. 我想在scala中执行2个独立的无限循环。 The first task takes about 1 second for each run and the second takes 0.5 seconds. 每次运行第一个任务大约需要1秒,第二个任务需要0.5秒。

Here is the code: 这是代码:

package future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object MyFuture {
  def task1(): Future[Unit] = Future {
    println("doing job 1")
    Thread.sleep(1000)
  }

  def task2(): Future[Unit] = Future {
    println("doing job 2")
    Thread.sleep(500)
  }

  def infiniteLoop(): Future[Unit] = {
    Future.sequence(List(task1(), task2())).flatMap(x => infiniteLoop())
  }

  def main(args: Array[String]): Unit = {

    Await.ready(infiniteLoop(), Duration.Inf)
  }

}

The output of the program 程序的输出

doing job 1
doing job 2
doing job 2
doing job 1
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2

I want the output of the job 2 to be twice as the output of job 1 because it takes half the time. 我希望作业2的输出是作业1的输出的两倍,因为它需要一半的时间。

What I can do to simulate 2 real independent process? 如何模拟2个真正的独立过程?

Consider using either java's scheduled executor to schedule tasks with fixed interval. 考虑使用Java的预定执行程序来按固定间隔计划任务。 Or you can use Akka if you need communication between this tasks. 或者,如果您需要在这些任务之间进行通信,则可以使用Akka。 BTW this code does what you ask: 顺便说一句,这段代码可以满足您的要求:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

/**
  * Created by hibou on 13/02/16.
  */
object MyFuture {
  def task1(): Future[Unit] = Future {
    println("doing job 1")
    Thread.sleep(1000)
  }

  def task2(): Future[Unit] = Future {
    println("doing job 2")
    Thread.sleep(500)
  }

  def loopTask1(): Future[Unit] = {
    task1.flatMap(_ => loopTask1())
  }

   def loopTask2(): Future[Unit] = {
    task2.flatMap(_ => loopTask2())
  }

  def infiniteLoop(): Future[Unit] = {
    Future.sequence(List(loopTask1(), loopTask2())).map(_ => ())
  }

  def main(args: Array[String]): Unit = {

    Await.ready(infiniteLoop(), Duration.Inf)
  }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM