Skip to content

Instantly share code, notes, and snippets.

@hnaoto
Created August 18, 2017 04:22
Show Gist options
  • Save hnaoto/4fbb8bb452bb502c16b7e54198614430 to your computer and use it in GitHub Desktop.
Save hnaoto/4fbb8bb452bb502c16b7e54198614430 to your computer and use it in GitHub Desktop.
import scala.collection.mutable.ArrayBuffer
import java.util.concurrent._
class Producer(queue :BlockingQueue[String]) extends Runnable {
val str = "item"
def run(): Unit = {
while(true){
try {
queue.put(str)
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer(queue: BlockingQueue[String]) extends Runnable {
def run(): Unit = {
while(true) {
try {
val item = queue.take()
consume(item)
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
def consume(item: String): Unit = {
println("consumed by: " + Thread.currentThread.getName())
}
}
object PC extends App {
val queue = new LinkedBlockingQueue[String]()
// One thread for the producer
val producer = new Producer(queue)
new Thread(producer).start()
val threads = 3
val pool = Executors.newFixedThreadPool(threads)
for (i <- 1 to threads) {
pool.submit(new Consumer(queue))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment