Created
August 18, 2017 04:22
-
-
Save hnaoto/4fbb8bb452bb502c16b7e54198614430 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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