A
A
adreSsS2021-05-26 17:35:40
Scala
adreSsS, 2021-05-26 17:35:40

Why is the program terminating?

object test {
  def main(args: Array[String]) {
    val buf: ArrayBlockingQueue[Integer] = new ArrayBlockingQueue(5)

    for (p <- 1 to 2)
      ExecutionContext.global.execute(() =>
        for (i <- 1 to 10) {println(s"Producer$p producing $i"); buf.put(i)}
      )

    for (c <- 1 to 3)
      ExecutionContext.global.execute(() =>
        for (i <- 1 to 10) {println(s"Consumer$c consumed ${buf.take}")}
      )
    Thread.sleep(1000)
  }
}

Hello, I have a question about the code above. Why is the program terminating?
I thought that the above program should hang because the ArrayBlockingQueue is empty, there are fewer Producers than Consumers and there is nothing more to remove from the Consumer queue.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question